Sei sulla pagina 1di 38

SAP Sourcing 9.

Scripting and Workflow Guide

March 2012 

© 2012 SAP AG. All rights reserved.


Table of Contents
1  Introduction ........................................................................................................................................... 4 
1.1  Intended Audience and Assumptions ..................................................................................................... 4 
1.2  Guide Layout and Conventions .............................................................................................................. 4 
1.3  Terminology ............................................................................................................................................ 4 
2  Scripting ................................................................................................................................................ 6 
2.1  Scripting Business Documents ............................................................................................................... 6 
2.1.1  Script Context .................................................................................................................................... 6 
2.1.2  Document Life Cycle.......................................................................................................................... 7 
2.1.3  Import Life Cycle ................................................................................................................................ 8 
2.1.4  Additional Script Control .................................................................................................................... 9 
2.1.5  Collections (Subordinate Classes) .................................................................................................... 9 
2.1.6  System-Set Variables ...................................................................................................................... 10 
2.1.7  System-Provided Methods............................................................................................................... 11 
2.2  Authoring a Script ................................................................................................................................. 12 
2.3  BeanShell Versus Java Styles .............................................................................................................. 12 
2.4  Handling Exceptions ............................................................................................................................. 12 
2.5  Localized Resources and Exceptions ................................................................................................... 14 
2.6  Use of Internal APIs .............................................................................................................................. 15 
2.7  Using Scripting to Assist with Mass Changes ...................................................................................... 15 
2.8  IBean Management .............................................................................................................................. 15 
2.9  Scripting Examples ............................................................................................................................... 16 
2.9.1  Logging Exceptions ......................................................................................................................... 16 
2.9.2  Independent Field Check ................................................................................................................. 18 
2.9.3  Dependent Field Check ................................................................................................................... 18 
2.9.4  Set Default Value ............................................................................................................................. 18 
2.9.5  Iterating Over a Collection (Exception Chaining)............................................................................. 19 
2.9.6  Adding to a Collection ...................................................................................................................... 19 
2.9.7  Dealing with Value Lists................................................................................................................... 19 
2.9.8  SAP Sourcing Types........................................................................................................................ 20 
2.9.9  Top-Level Category Check .............................................................................................................. 21 
2.9.10  Prevent Changing from or to a Status ............................................................................................. 21 
2.9.11  Explicitly Called Scripts.................................................................................................................... 22 
3  Workflow .............................................................................................................................................. 24 
3.1  Workflow-Enabled Business Documents .............................................................................................. 24 
3.2  Workflow System Functionality ............................................................................................................. 24 
3.3  Overview of the XPDL File.................................................................................................................... 24 
3.4  Workflow Definitions ............................................................................................................................. 25 
3.5  Workflow Development Cycle ............................................................................................................... 25 

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 3

3.6  Scriptable Functionality ......................................................................................................................... 26 


3.7  Scripting Workflows .............................................................................................................................. 26 
3.7.1  Pre-Phase Change Scripts .............................................................................................................. 26 
3.7.2  XPDL Embedded Scripts ................................................................................................................. 26 
3.7.3  System-Set Variables ...................................................................................................................... 28 
3.7.4  System-Provided Methods............................................................................................................... 28 
3.7.5  Scripting Transitions ........................................................................................................................ 29 
3.7.6  Special Considerations for Contract Documents ............................................................................. 30 
3.7.7  Workflow Metadata .......................................................................................................................... 31 
3.7.8  Ad-Hoc Approvals ............................................................................................................................ 31 
3.8  Workflow Examples .............................................................................................................................. 32 
3.8.1  Prescript ........................................................................................................................................... 32 
3.8.2  Postscript ......................................................................................................................................... 33 
3.8.3  PreCancelScript ............................................................................................................................... 33 
3.8.4  Change Approver ............................................................................................................................. 33 
3.8.5  Getting the Submitter of a Workflow ................................................................................................ 34 
Appendix A: Scripting Guidelines ............................................................................................................... 35 
A.1 Design ....................................................................................................................................................... 35 
A.2 Writing Scripts ........................................................................................................................................... 35 
A.3 Exceptions ................................................................................................................................................. 35 
A.4 General...................................................................................................................................................... 35 
Appendix B: Utility Classes .......................................................................................................................... 36 
Copyrights, Trademarks, and Disclaimers....................................................................................................... 37 

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 4

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.1 Intended Audience and Assumptions


The intended audience for this document is technical users who are Java programmers with experience in
creating and parsing XML documents. SAP also recommends familiarity with the BeanShell user guide. For
an overview and detailed BeanShell documentation, see http://www.beanshell.org. Additionally, some of the
techniques described in this document require knowledge of SQL.
An in-depth knowledge of SAP Sourcing customization features, such as extensions, extension collections,
and page customizations, is recommended. In addition, a conceptual understanding of SAP Sourcing
business documents is required, including configurable phase definitions and collaborator roles.
Configuration experience is also required, including script testing and system log review

1.2 Guide Layout and Conventions


This guide provides scripting and workflow information in separate sections. However, these processes are
linked and overlap conceptually.
This guide is intended to supplement the information in the SAP Sourcing Online Help. You can enter
important/helpful information that is new for this component release.

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.
Extension collection: A collection that is user defined. Scripting interacts with these collections via the
ExtensionCollectionIfc interface.
Document (syn. Business Document, Object): An instance of the class.
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.
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.
Home: A class that manages Lifecycle tasks related to its associated IBean. Every IBean has the Home
interface.
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.
Script manager: The part of the underlying application that manages the script from creation to finish.
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 class’s accessors. Members of these collections may have IAPI-defined types.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 5

Workflow definition: The object in SAP Sourcing that represents the XPDL-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.
XPDL: A format designed for the interchange of Business Processes.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 6

2 Scripting
2.1 Scripting Business Documents
Scripts are executed at key times in the lifecycle of an SAP Sourcing document. Although scripting is not
supported by every class in the SAP Sourcing application, the main classes are scripting enabled. During
script definition, classes available for scripting are provided in a drop-down list

2.1.1 Script Context


The point at which a script is executed is its scripting context. The script manager will set certain variables in
the script, depending on the context. The following table summarizes the available scripting contexts.

Context Description

A script at the field level executes when the document is fully


validated typically during save or before a phase change in a
Field Validation business document that supports configurable phases.

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(),
Field Data Edit it returns Project Foo.

As with a field context, when a collection is scripted, the script


executes if a collection changes or when the parent document is fully
Collection Validation validated.

Document Lifecycle
Event A document script executes as dictated by the target lifecycle.

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
Toolbar business documents. Collections do not support toolbar scripts.

A script that executes during data import as dictated by the target


lifecycle. Import lifecycle scripts allow access to inbound data and
Import Lifecycle Event newly created business objects.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 7

2.1.2 Document Life Cycle


The Document Life Cycle (DLC) refers to the stages a class can pass through in the normal course of user
interaction. When a script is defined for the Document Scripting Context, a target DLC event must be
selected. Not every DLC event is available to all objects. However, the allowable events are available during
script definition, as described in the following table.

Event Description Notes/Examples

Of limited use, as the document is not


changeable at the time it is loaded.
Point at which the document is loaded
and not editable, for example, when
selecting a project from the My Caution
Projects picker. A number of internal Extreme care should be exercised, as
processes invoke this event, such as scripting this event can cause
the daemon responsible for pushing performance issues and other
Loaded document security template changes. undesirable effects.

Ideal time to provide alternative


defaults. Does not execute when the
Point at which the class is instantiated Create from Template or Document
Created as new Duplicate actions are performed.

Creation of a document using the As with the Created event, this is a


Duplicate button or Create from good opportunity to provide alternative
Duplicated Template option. defaults.

On business documents that support Scripts that raise exceptions in this


configurable phase definitions, a script context stop the phase change from
that executes prior to the phase occurring. In addition, the document is
Pre Phase change. RFx and Auction phases are fully validated prior to this script, which
Change not included. includes the execution of any scripts.

As the phase change has already


occurred and the document is fully
validated, no additional validation
should be done at this time and no
Post Phase Script that executes immediately after changes should be made to the
Change the phase change document.

The business document is saved prior


to the execution of this script. Any
On business documents that support exceptions that are raised in this
Pre Publish publishing to ERP, a script that context stop the publishing from
to ERP executes prior to the publishing. occurring.

Document validation scripts run when


the document changes and the user Useful for field validations that are
saves the document, or another action dependent on each other. This is the
Validated is taken, such as a phase change, that final point at which changes can be
invokes a validation. made safely by a script.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 8

Event Description Notes/Examples

This script is most useful for integration


to other systems, because the
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
Once the documentation passes business document affect the post-
validation and is stored in the saved version and cause confusion for
Saved database, this script executes. users.

2.1.3 Import Life Cycle


Similar to the Document Life Cycle, a series of events are associated with data import. Different points in the
life cycle allow access to different objects and data. There are two main categories of events: “record”
events and “iBean” events. Record events occur before a business object has been constructed and only
allow access to an “import record” containing the inbound data. iBean events occur after the object has
been constructed and is available to the script as an instance of IBeanIfc. In the script code, the iBean will
always be available in the variable “doc”, as with other scripting events. The record, which implements
ImportRecordIfc, is available in the variable “import_record”.

Event Description Data Context Notes/Examples


The init hook allows
scripting at the beginning
of file processing. There
is no record or ibean data
available. Xan be used
to validate environmental Of limited use, as no
Init variables, for example. None record data is available.
Allows access to inbound
data before the iBean
Pre-Process Row has been created. Record
Gives the opportunity to
Should Process reject the import of a The script must return a
Row particular row. Record Boolean object .
Gives the opportunity to
manipulate the newly
constructed iBean before
Process Row it is saved. iBean
Gives the opportunity to
reject the save of a The script must return a
Ok To Save particular iBean iBean Boolean object.
Gives the opportunity to Could be used to write out
act on the iBean *after* it custom log information, or
Save has been saved. iBean send custom notifications.
This is the mirror image
of the Init event. Allows
scripting after the import
of the entire file has
Final completed. None

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 9

2.1.4 Additional Script Control


During script definition, the user can select other ways to determine when the script executes. Not every
class supports these limits. For example, Document Type can be a limit for only those documents that
support types. Refer to the following table for limits and their supported classes.

Limit Description Script Classes


Context Supported

Instance Type Options are Document only, All Classes that


Template only, and Any. support
templates

Document Type A list of defined document types All Classes that


for the selected class support types

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.

2.1.5 Collections (Subordinate Classes)


There are two types of collections in SAP Sourcing: system and extension. Each row of data in a collection is
called a member. Access to the collections is either via the provided accessor method in IAPI, or, for
extension collections, via the getExtensionCollection(“logical name”) method.
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:

Scripting Class Target


Context

(A) Collection Supplier CERTS

(B) Document CERTS (all lifecycle events)

(C) Field/Field CERTS (target field)


Data Edit

• Script A executes during validation of supplier when the collection changes.


• Script B contains all the events discussed under Document Life Cycle and executes for the specific
member in accordance with those events.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 10

• Script C executes when the target attribute changes on the collection member.
It may seem intuitive that script B, with the validate DLC event, is preferred over script A, as it only executes
for any changed member, but the overhead associated with the Script Manager actually results in reduced
performance. Script A is the preferred way to validate collections.

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”);

2.1.6 System-Set Variables


The creation and execution of scripts is managed by the Script Manager object, transparent to the developer.
When the Script Manager prepares the script for execution, it presets certain variables applicable to the
selected context and event. The following table summarizes these variables.

Context Event Variable Description

Reference to the
current document
being scripted, also
All All doc called an IBean

Instance of
IapiSessionConte
xtIfc for the current
All All session user’s session

Reference to
document that is
Document Duplicated otherDoc being duplicated

String representing
internal ID of current
phase of document.
In the Pre-Phase
context, this is the
current phase. In the
Pre and Post Post-Phase context, it
Document Phase Changes current_phase is the new phase.

String representing
internal ID of target
phase of document in
Pre-Phase change
script or previous
Pre- and Post- phase in Post-Phase
Document Phase Changes other_phase change script

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 11

Context Event Variable Description

Boolean set to true if


Pre- and Post- phase_advancing the phase change is
Document Phase Changes forward

Reference to the
Field & Field Data IBeanFieldMdIfc
Edit field for field in question

Reference to value of
field in question. In
the case of Field Data
Field & Field Data Edit, this is the old
Edit fieldValue value of the field.

Reference to new
Field Data Edit newFieldValue value

Reference to
collection being
scripted
Collection collection

2.1.7 System-Provided Methods


In addition to the preset variables, the script environment offers preset methods described in the following
table.

Method Description Notes

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. SimpeObjectRefenceIfc,
AmountIfc, PriceIfc,
AttachmentIfc,
EnumTypeIfc,
ResourceIfIfc,
SysDateIfc,
SysDatetimeIfc,
SysTimeIfc

getFieldValue() In Field and Field Data Edit Not normally used, as variable
scripts, returns the value of fieldValue accomplishes this
field

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 12

Method Description Notes

setFieldValue(Object In Field and Field Data Edit


object) scripts, sets value of field to
specified value

createApplicationExcepti Creates an exception on There is no real convenience in


on(String attr, msgid) specified attribute using this method. See Scripting
specified localized resource Examples (page 16) for
exception examples.

2.2 Authoring a Script


The approach to scripting should mirror other custom code development and follow a standard process that
includes design, customer sign-off, and testing. The advantage of BeanShell scripting is that it enables faster
development because the script is developed for a specific customer implementation. The configuration of
SAP Sourcing for a specific customer should guide the script. For example, if the SAP Sourcing
implementation has a required field, the script should not test for null and raise an error, because the
application ensures that the field always has a value. Decisions like this should always be based on the
developer’s best judgment. However, it is not necessary to develop a script to consider theoretical
possibilities unless there is a valid reason to do so.
SAP recommends that an external editor be used to develop scripts. When the script is ready for testing, it
should be cut and pasted from the editor into the script definition and saved there. If there are syntactic
issues, such as mismatched braces, the SAP Sourcing application provides an error indicating the line
number.
Scripts should never be developed in a production environment. Scripts interact with live data and should
only be deployed to production once fully tested.
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).

2.3 BeanShell Versus Java Styles


The BeanShell language offers a number of shortcuts to facilitate faster development. For example, there is
no enforcement of type cast variables. Refer to the BeanShell documentation (http://www.beanshell.org) for
a full description of the BeanShell language.

2.4 Handling Exceptions


SAP Sourcing has its own implementation of the ApplicationException. There are exception creation
methods for each business document. See the IAPI Java Documentation in the SAP Sourcing Reference
Guide (RG) for the method signatures.
When any exception is raised and not caught in the script, it is propagated to the UI. A
ChainedApplicationException and its subclasses are processed by the UI to highlight the attribute in
error, for example. Other exceptions are displayed in a raw format.
The following approaches can be used to handle application exceptions:
• Raise the exception and stop the script.
• Validate the whole document and raise all at once (chaining exceptions).

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 13

Example
The following code samples are provided to illustrate exception features.

// Creates an exception under a field APPROVAL_SIG

throw doc.createApplicationException(“APPROVAL_SIG”,
“custom.exception.approval.required”);

// Displays a message at the top of a document

throw new ApplicationException(session,


“custom.exception.export.failed”);

// Chains an exception to a root exception and throws that root


// exception at the end

ae = new ApplicationException(session);
ae.chainAtEnd(doc.createApplicationException(“APPROVAL_SIG”,
“custom.exception.approval.required”));

if(ae.getChain() != null) throw ae.getChain()


For field data edits and field validation, the script itself puts the message under the scripted field. However,
SAP recommends that the exception be created for the field being scripted for the sake of clarity. In the case
of document validation scripts, the developer can choose the preferred approach based on blocking errors
and other dependencies.

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.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 14

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 */

/// … script ommitted


The comment should describe the event precisely. The comment in the example above indicates that the
issue occurred in a field validation on the Display Name field. At this point, the user can easily relay the text,
but the actual exception is in the system log.

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.

2.5 Localized Resources and Exceptions


Because SAP Sourcing is designed as a localized application, strings of text are represented as localized
resources. To specify the localized resource to be used for an exception, the methods for raising the
exception are based on certain assumptions about the provided ID.

Example
In the following example, SAP Sourcing presents the error in the language of the current user’s
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”);

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 15

2.6 Use of Internal APIs


SAP does not recommend the use of internal APIs for the following reasons:
• They are for internal use only.
• They are undocumented.
• They are subject to change without notice.
• They are unsupported.
• They can result in corrupt data when used incorrectly.
If there is a need for an object not covered in the IAPI JavaDoc, contact Customer Support using SAP
Support Portal (http://service.sap.com).

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.

// Need access to the CURRENCY on the User Account


//
acct = IBeanHomeLocator.lookup(session, user).find(user);
import com.frictionless.api.usermgmt.masterdata.UserAccountIBeanIfc;
curr =
acct.getFieldMetadata(UserAccountIBeanIfc.sPROPID_CURRENCY).get(acct);
If there is no property for the attribute you require, contact Customer Support using SAP Support Portal.

2.7 Using Scripting to Assist with Mass


Changes
Using standard data importers over scriptable objects offers the developer a powerful tool to effect a global
change. No new concepts are needed to create such scripts; all scripts defined for the object being imported
execute just as they would if the object was created, or updated, from the UI. That is, for each record in the
import file, all related scripting contexts will execute just as if the object was edited through the UI. This
benefit can also cause unintended issues, because scripts designed with the interactive user in mind
execute during import as well as during the UI interaction. Because there is no way to detect this context, the
developer must consider both possible execution scenarios.

2.8 IBean Management


Almost every IBean in the system has a Home Interface for finding, modifying, and creating instances of
those beans. The Home Interface acts as a factory class for creating and duplicating IBeans, as well as
offering some other supervisory methods that act on IBeans.
The methods can vary for each business document. For example, the ProjectIBeanHomeIfc offers
cancel(…), changePhase(…), close(…) methods, that are particular to that business document only.
The IBean’s home can be obtained in the following ways:
• If an Object Reference to the desired IBean is known:
userHome = IBeanHomeLocator.lookup(session,
doc.getDocumentOwnerUserReference());
• If an Object Reference to the IBean is not available, the static field, sHOME_NAME is used:
// Get Link
//
linkDefnHome = IBeanHomeLocator.lookup(session,
DocumentLinkDefinitionIBeanHomeIfc.sHOME_NAME);

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 16

• If an instance of the IBean is available, for example, the variable doc, the home can be accessed as:
// Change phase,
//
doc.getIBeanHome().changePhase(doc, “bid_solicitation” );

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());

// Find by Unique Document Identifier


//
linkDefn = linkDefnHome.findUnique("FCI-BIZ2 RELATED");
Modify the retrieved IBean, upgrade it to edit, save it, and downgrade it to view, as follows:
// Change the email address
//
owner = userHome.find(doc.getDocumentOwnerUserReference());
userHome.upgradeToEdit(owner);
owner.setEmail(“foo@bar.com”);
userHome.save(owner);
userHome.downgradeToView(owner);
To create a new IBean, do the following:
// Create a new user account.
//
newUser = userHome.create();
newUSer.setName(“loginid”);
...
userHome.save(newUser);
To duplicate a project, do the following:
// Duplicate this project
//
newProject = doc.getIBeanHome().createFromAnother(doc);

2.9 Scripting Examples


This section provides script examples and introduces concepts based on actual scenarios.

2.9.1 Logging Exceptions


SAP Sourcing maintains log files during normal operations and developers can utilize these to store logging
information from the script. As there is a performance impact with rigorous logging, scripts should log only in
the following circumstances:
• For testing purposes (to be removed in the production script)
• To record errors that the end user cannot deal with, such as a third-party application being offline
Do not log for every script if it is not necessary.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 17

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”);

// Convenience method - Errors


//
logError(msg) {
log.setLogMessage(error);
Logger.error(log);
}

// Convenience method - Informational


//
logInfo(msg) {
log.setLogMessage(error);
Logger.info(msg);
}

/** Main script */

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 (page 12) for further details on exception handling.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 18

2.9.2 Independent Field Check


Scenario: an integer field must be between 0 and 60.
This extension is of type Integer and the allowable values are restricted. BeanShell saves the developer from
having to obtain the primitive int value out of the integer object.
The following is the field validation script on extension TERM_PERIOD:
/*
* Validate that the field is between 0 and 60
*/
if(hasValue(fieldValue) @and (fieldValue < 0
@or fieldValue > 60))
throw doc.createApplicationException(field.getAttributeId(),
"custom.invalid.term.period");

2.9.3 Dependent Field Check


Scenario: FIELDA is anything at all, then FIELDB must be specified.
Dependency checks require special consideration. Although it might seem that a field validation script on
FIELDA would suffice, such a script only executes when FIELDA changes. If the script succeeds when the
document is first saved, the user blanks FIELDB, and no error is raised because FIELDA did not change.
This problem suggests the following rule: if validation is conditioned on anything outside of the field being
validated, it must be part of the document validation script.
// Document Validation Script, one field depends on another

FIELDA = doc.getExtensionField(“FIELDA”).get();
FIELDB = doc.getExtensionField(“FIELDB”).get();

if(hasValue(FIELDA) @and !hasValue(FIELDB)) {


throw
doc.createApplicationException(“FIELDB”,”exception.value.is.required”)
;
}

2.9.4 Set Default Value


Scenario: Set the currency of the document to the creator’s default currency.
Setting default values is simply a matter of setting the values in a script. Any defaults that were set by the
application are overwritten, because the created script executes last.
The following script shows how to access a field via the metadata of the object. This should be done only
when an accessor is not provided in the IAPI Framework. Whenever this is used, a request should be sent to
SAP Support with an indication of the IBean and the required property to be exposed in a future patch or
release.
The example script assumes that a session always has an account associated with it. The script developer
does not need to account for the possibility of a null value. Similarly, because currency is a required field on
the user account, it is not required to test for a null value for currency.
The following is the document created script:
// Set the user default currency
//
user = session.getAccount().getAccountObjectReference();
acct = IBeanHomeLocator.lookup(session, user).find(user);

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 19

// Set default currency


//
import com.sap.odp.api.usermgmt.masterdata.UserAccountIBeanIfc;
curr =
acct.getFieldMetadata(UserAccountIBeanIfc.sPROPID_CURRENCY).get(acct);
doc.setCurrency(curr);

2.9.5 Iterating Over a Collection (Exception Chaining)


Scenario: Check each row of a collection and if FIELDA is blank, raise an error on that row and cell.
The following example provides a basic pattern for this common type of script (collection validation script):
// The exception chain. Chain all exceptions to this one
//
exception = new ApplicationException(session);

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"));

}
}

// Handle the exceptions


//
if(exception.getChain() != null) {
throw exception.getChain();
}

2.9.6 Adding to a Collection


The following example provides a basic pattern for collection member creation:
// Create a new member in a collection
//
colln = doc.getExtensionCollection("my_collection");
newMember = colln.create();
newMember.set("FIELDA","GM Corporation");
colln.add(newMember);

2.9.7 Dealing with Value Lists


Value lists are presented to the user in the localized language. When a script accesses a value list value, it
returns a localized reference, which has no reliable display name.
lref = doc.getStatus();

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 20

// Prints what the user sees


print(lref.getDisplayName(session));

// Can sometimes print null


print(lref.getDisplayName());

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 value’s 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

// Display Name, absolute ID, of the Completed status

STATUS_COMPLETED = "Completed";

if(hasValue(fieldValue) @and IBeanHomeLocator.lookup(session,


fieldValue).find(fieldValue).getDisplayName().equals(STATUS_COMPLETED)
{

// … DO SOMETHING …
}

// DON’T DO – This *will* break at some point

if(hasValue(fieldValue) @and
fieldValue.getDisplayName().equals(STATUS_COMPLETED)) {

// … DO SOMETHING …
}

2.9.8 SAP Sourcing Types


When a SAP Sourcing data type is needed, use the TypeFactory class, as follows:
// Create a link on this Project to the new RFQ
//
newLink = doc.getDocumentLinkList().create();
newLink.setDisplayName( rfx.getDisplayName() );
newLink.setLinkDate(TypeFactory.createSysDatetime(new
java.util.Date()));
...

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 21

2.9.9 Top-Level Category Check


Scenario: Ensure that the selected category is not top level, to force the user to pick a category at the lower
level.
The following shows field validation on Internal Category field:

// Check to make sure the Commodity (Int Cat) is not at the top level
//

if(!hasValue(fieldValue)) {
return;
}

intCatHome = IBeanHomeLocator.lookup(session, fieldValue);


categoryIBean = intCatHome.find(intCat);

if(!hasValue(categoryIBean.getParentObjRef()) ) {
throw doc.createApplicationException(field.getAttributeId(),
"custom.top_level_commodity_not_allowed");
}

2.9.10 Prevent Changing from or to a Status


2.9.10.1 Scenario: Once a project is in a completed state, permit state changes to be
performed only by users in a valid group.
The issue that arises from this script is that it executes during duplication. If the project being duplicated is
completed, the script executes and stops the process.
To prevent this problem, the project must be identified as new and allowed to be saved. The easiest way to
accomplish this is to attempt to find the same IBean in the database.
The following is the field data edit script on the Status field:
// If this project is not in the database then return,
// as it was just created and we have to be more
// forgiving to allow the defaulting to take place
//
persistentDoc = doc.getIBeanHomeIfc().find(doc);
if(persistentDoc == null) {
return;
}

// Determine if the current user a member of admins


//
reportingGroups = new String[] { "sys_admins", "reg_admins",
“buyer_managers"};
import com.sap.odp.api.usermgmt.masterdata.GroupIBeanHomeIfc;
groupHome = IBeanHomeLocator.lookup(session,
GroupIBeanHomeIfc.sHOME_NAME);
isReportingUser = false;
for (int i = 0; i < reportingGroups.length; i++) {
currentGroup = groupHome.findGroup(reportingGroups[i]);

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 22

if (hasValue(currentGroup) @and
currentGroup.findGroupMembers().contains(
session.getAccount().getAccountObjectReference()) ) {
isReportingUser = true;
break;
}
}

// If new status is in Completed Phase, make sure the


// user is a member of one of the reporting groups
//
if (!isReportingUser
@and hasValue(newFieldValue)
@and IBeanHomeLocator.lookup(session,
newFieldValue).find(newFieldValue).getDisplayName().equals("Completed"
) ) {
throw doc.createApplicationException("STATUS",
"custom.cannot.change.to.completed");
}

// If the status is already in completed, make sure only reporting


members can
// change it
//
if (!isReportingUser
@and hasValue(fieldValue)
@and IBeanHomeLocator.lookup(session,
fieldValue).find(fieldValue).getDisplayName().equals("Completed")
@and !fieldValue.equals(newFieldValue)) {
throw doc.createApplicationException("STATUS",
"custom.cannot.change.from.completed");
}

2.9.11 Explicitly Called Scripts


Explicitly Called Scripts is a scripting object type that is not attached to a specific business document or
context. It is a standalone script that can be executed from a scheduled task on a designated schedule.

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 tab Æ Integration area Æ Explicitly Called Script.
2. On the Explicitly Called Script screen, choose the New button.
3. Enter the required information and your script and save your work.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 23

To trigger the script:


1. Choose Setup Æ System Setup tab Æ Scheduled Tasks area Æ Scheduled Tasks.
2. Create a scheduled task of the type Explicitly Called Script Execution.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 24

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 workflow’s 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.
Workflow partly utilizes a standardized format of a process definition called XPDL 2.0 (see
http://en.wikipedia.org/wiki/XPDL). SAP Sourcing links to an open source utility called Together Workflow
Editor CE for purposes of creating and editing process definitions. The XPDL file defines the steps the
workflow must go through and the scripts for adding the required approvers at each step.
The process of creating and assigning workflow definitions is described in this guide. For more detailed
information, see the SAP Sourcing Online Help.

3.1 Workflow-Enabled Business Documents


The following business documents are workflow enabled:
• Projects
• Contract documents (under master agreements and agreements)
• User-defined business documents 1 through 5

3.2 Workflow System Functionality


The system functionality relating to workflow processing is generally not changeable by scripting. System
functionality refers to the following:
• Locking and unlocking of the document during the approval process
• Processing approvals or rejections and changing the status of the approval process
• Email notifications

3.3 Overview of the XPDL File


The XPDL contains activities, represented by green or blue boxes, and transitions, represented by arrows.
For the SAP Sourcing implementation, parallel approvals are not supported. Therefore, any activity must
transition to the end or to the next activity. Blue activities are block activities and are required as the
penultimate stage based on the XPDL specification. They are not treated differently by the workflow engine,
but do act as a focal point for all transitions prior to the end of the process.
The following figure shows a multi-activity workflow. In this workflow, each subsequent activity checks
something in the parent document to decide if that activity is required. If an activity does not result in the
addition of an approver, it is skipped. If an activity is rejected by the approvers, the workflow ends.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 25

In the following figure, there is only one activity:

SAP recommends that you use the templates provided as the basis for workflows, as opposed to creating
new ones.

3.4 Workflow Definitions


The Workflow Definition is the Sourcing document that is associated with the workflow process defined in the
XPDL file. Besides the information in the attached XPDL file, the workflow definition requires some additional
information, as follows:
• The role for any approver added by the workflow
• The role those approvers revert to post-workflow
• The process owner (this can usually remain set to the default)
Approvers can be both individual users and groups. If groups are used, the collaborator role for approver
must be configured to Allow Multiple.

3.5 Workflow Development Cycle


A typical development process employs an XPDL editor to create the XPDL file from an existing template. As
with scripting, SAP recommends that you use a text editor to create the scripts before pasting them into the
XPDL Extended Attributes. When the workflow is ready for testing, the workflow definition is created or
updated with the new XPDL file. The Current Workflow Processes report is a tool used to delete failed
workflow processes and allow repeat testing.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 26

3.6 Scriptable Functionality


Because the core workflow functionality is immutable, in a most basic sense the role of scripting is to add
approvers to the document. The logic behind this is based on customer requirements and can be quite
simple or extremely complex. Nevertheless, the result of the script is to add none, one, or more approvers to
the document.

3.7 Scripting Workflows


3.7.1 Pre-Phase Change Scripts
Because the workflow engine locks a document as soon as it enters workflow, the pre-phase change event
is the last point at which to ensure the document is ready for workflow. For example, if there are values that
are not normally required in a document, such as Total Contract Value, but that are required before
approvals are sought, SAP recommends that you confirm there is a value in this field in the pre-phase
change event and raise the necessary exceptions. By doing this, you prevent the document from being
locked, which would potentially require the intervention of a system administrator who can delete the
process.

3.7.2 XPDL Embedded Scripts


XPDL embedded scripts are scripts that are embedded as extended attributes in XPDL Activity elements.
The following table lists the extended attributes that can contain scripts.

Extended
Attribute Description

Prescript Adds required approvers to the activity it is associated with

Performs any actions that might be needed after an activity


is completed, but has not transitioned to the next activity, or
the end of the workflow. This is usually needed only on the
final activity, for example, to advance the phase
Postscript automatically.

When a script is canceled via the Current Workflow


Processes report, or by an action in a prescript or postscript,
the PreCancelScript executes. This may, for example,
PreCancelScript move the document back to a prior phase.

Usually not required if the block activity is used as the final


activity in a process. In the simple workflow shown above,
this extended attribute is required. See Scripting Transitions
TransitionCondition (page 28) for more information.

In addition to these extended attributes, there are informational attributes that are optional, but are used in
the workflow history or general email notifications to approvers.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 27

Extended Attribute Description

A string that represents a resource ID


(bundle$resource_id) in SAP Sourcing, such as
custom$workflow.desc. This description is
LocalizedDescription added to the approver’s notification email.

Non-approval workflows are beyond the scope of


this document. In general, such a requirement is
better suited to a pre- or post-phase change script.
ApprovalActivity Omit this attribute or set it to TRUE.

The unit of duration expected for this activity. This is


stored in the workflow history and may be a useful
Duration metric for analysis.

M,D,Y. The unit of measure for the Duration


DurationUnit attribute.

A string that represents a resource ID


(bundle$resource_id) in SAP Sourcing, such as
custom$workflow.instr. These instructions are
LocalizedInstructions added to the approver’s notification email.

The following figure shows a typical activity’s extended attributes:

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 28

3.7.3 System-Set Variables


When the workflow script is being prepared for execution, the system sets certain variables, as indicated in
the following table.

Variable Description

doc Reference to current document under workflow

An instance of IapiSessionContextIfc for the


current user’s session. In a script, that session is not
the user who submitted the workflow but rather the
workflow engine. See Workflow Examples (page 32)
for ways to access information about the actual
session submitter.

String representing XPDL attribute ID for current


nativeId activity

String representing XPDL attribute Name of current


nativeName activity

Reference to current step in approval process and


workItem only available in PostScript activity

3.7.4 System-Provided Methods


The following table lists the methods provided by the system to aid development of the workflow script.

Method Description Notes

Returns an int value The values returned are adapted


representing the current status from the
of the activity. Used only in ApprovalStatusEnumType
getApprovalStatus() transitions. class.

Adds the specified principal to


the list of approvers. The
principal must be an object principle must be an instance of
reference to a group or a user an ObjectReferenceIfc that
(see Workflow Examples on refers to GroupIBeanIfc, or
addApprover(principal) page 32). UserAccountIBeanIfc

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 29

Method Description Notes

Overloaded variant of the


previous method. The addition of
rule controls whether all
approvers must approve or any
of the approvers can approve
the activity (see the prescript rule is an instance of
example in Workflow Examples CollaboratorApprovalRule
addApprover(principal, rule) for details). Type

Provides a way of canceling the


workflow process in-script. This comment is a Java string. That
results in execution of the string is stored in the workflow
cancelProcess(comment) PreCancelScript. history of the document.

3.7.5 Scripting Transitions


Transitions represent the progression of the workflow process from the current activity to the next activity or
the end. Each time a user approves or rejects the document under workflow, or if the workflow process is
canceled, an event notifies the workflow engine, which runs as a daemon process. The workflow engine
determines the new status of the activity based on the approver actions. After determining the new approval
status for the activity, it evaluates the transition condition. The transition contains the condition that is tested
after this evaluation. For example, if an activity added a single approver and that approver approves the
document, the activity is an approved status.
As you see in the following figure, the XPDL specification for transitions provides an Expression attribute,
which is utilized by workflow to condition the transition.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 30

This expression must only be getApprovalStatus(), followed by a Java operator (== or != ) and one of
the statuses described in the following table.

Status Description

Pending
Activity is still pending user action.

Denied
Activity is rejected.

Approved Activity is approved.

Completed Non-approval activity was completed (not used).

In a multi-activity workflow, there are two transitions from each activity except for the last activity (refer to the
figure above depicting a multi-activity workflow). Each activity transitions based upon being approved or
denied, except for the last activity which transitions to the end only when the activity is not pending (its
precise status is not required at this point as this is the only way out of the workflow).
For a single activity workflow, the TransitionCondition is defined as an extended attribute, but contains
the same transition condition code.

3.7.6 Special Considerations for Contract Documents


Contract documents represent a special case for workflow. This business document is by nature subordinate
to a parent master agreement or agreement (the container document). Although the phase changes and
workflow history is tracked at the contract document level, the approvers are kept at the container level.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 31

When a script executes, the variable doc is the contract document IBean. If access is needed to the
container, as is often the case, a reference to it can be obtained as follows:
if(hasValue(doc.getParentIBean()) {
parentContainer = doc.getParentIBean();
else {
// Handle parent-not-loaded condtn here
cancelProcess(“Parent Document not loaded. Contact a System
Administrator.”);
return;
}
There is a possibility that the contract document can be loaded without its container, so handling the null
cases is mandatory.

3.7.7 Workflow Metadata


A common requirement is to be able to define the rules for the workflow in a dynamic way, such that
changes to them do not require experience with the XPDL process and scripting knowledge. The
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

Supervisor Recurring 0 100000 Managers


agreement

Buyer Recurring 0 100000 Supervisors


agreement

Manager NDA 0 0 Legal

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.

3.7.8 Ad-Hoc Approvals


When a document enters a workflow phase, each collaborator added prior with the role of approver must
manually approve the document in addition to the approvers in the workflow definition, regardless of the
approval rules in the workflow definition.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 32

3.8 Workflow Examples


3.8.1 Prescript
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();

// Get the workflow metadata


//
company = IBeanHomeLocator.lookup(session,doc.getCompanyRef()
).find(doc.getCompanyRef() );
workflowColln = company.getExtensionCollection("APPR_ROUTING");

// Group is added as ANYONE CAN APPROVE. ANY = 1 means all


// must approve.
//
ANY = 0;

// Go through the metadata and look for a match


// More than one match is OK
//
iterator = workflowColln.iterator();
found = false;

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) {

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 33

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.
// If not denied move forward to RFP status
//
if(getApprovalStatus() != DENIED)
{
home = IBeanHomeLocator.lookup(session,
ProjectIBeanHomeIfc.sHOME_NAME);
home.upgradeToEdit(doc);
home.changePhase(doc, "RFP");
IapiDocumentLockManager.lockField(session,doc,"FundingRequest");

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");

3.8.4 Change Approver


3.8.4.1 Scenario – When it is necessary to reassign a workflow item
Workflow items are created in a workflow process when an approval action is required. The change
Performer feature/API is used to reassign a workflow item for one user (user 1) to a different user (user 2).
User 2 becomes responsible for processing the workflow item. During the substitution, user 2 is added as a
collaborator, emails are sent to both users, and a workflow history entry is created.
WorkflowItemIBeanHomeIfc workflowItemHome = (WorkflowItemIBeanHomeIfc)
IBeanHomeLocator.lookup(userSession,
WorkflowItemIBeanHomeIfc.sHOME_NAME);
WorkflowItemIBeanIfc workflowItemBean = (WorkflowItemIBeanIfc)
workflowItemHome.findByUniqueDocName(taskId);
workflowItemBean.changePerformer(substituteAccount.getAccountObjectRef
erence());

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 34

3.8.5 Getting the Submitter of a Workflow


The variable session at the time a workflow script is executing does not refer to the same session as the
user who submitted the workflow; rather, it is a user who executes the daemon process responsible for
handling workflow.
It is often necessary to obtain the user who submits the workflow. The following script shows how to obtain
this value.
/*
* Gets the Submitter of the script
*/
getSubmitter() {
processHome = IBeanHomeLocator.lookup(session,
WorkflowProcessIBeanHomeIfc.sHOME_NAME);
process = processHome.findByNativeId(nativeId);
return process.getCreator();

submitter = getSubmitter();

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 35

Appendix A: Scripting Guidelines


A.1 Design
• Document script designs, from requirements through testing, and follow normal project approval
processes.
• Test completely in non-production environments before migrating.
• When choosing a scripting context, favor the context that results in the fewest instances of the
script needing to be created in a typical scenario.
• Log messages sparingly in production code.

A.2 Writing Scripts


• Do not put authorship or long descriptions in the script. Use the Description field on the script
definition.
• Use an external editor to develop and format scripts.
• Always test Value List Values using the Display Name.
• Use hasValue() to test objects for valid or non-null values.
• Do not write scripts that cover all possibilities. Let the application configuration govern the script,
but comment code when you make assumptions.
• Never raise exceptions or alter data in the post save context.
• Consider both the UI and background tasks when authoring scripts.

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 object’s 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.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 36

Appendix B: Utility Classes


The following table lists the utility classes that are part of the IAPI library. Unless relevant, the method
signature is omitted from the table. All methods are accessed statically.
See the IAPI Javadoc in the SAP Sourcing Reference Guide online documentation for detailed information
on the method parameters and so on.

Utility Class Method of Interest Description


Provides different ways to
IapiAccountLocator lookup(…) locate a user account
Provides functionality to lock
and unlock business
documents or parts thereof.
Useful in workflow, for
example, to lock a value field
that was integral to the
IapiDocumentLockManager All approval.
Provides functionality to
All except access system properties
initSystemServices() which and other information about
IapiSystemUtilities should not be used. SAP Sourcing environment
Used to retrieve the home
IBeanHomeLocator lookup( … ) interface for a specific class
Similar to the Log4j API,
provides access to SAP
Logger All Sourcing logging facility
Common API to create SAP
TypeFactory All Sourcing specific types

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 37

Copyrights, Trademarks, and Disclaimers


© 2012 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any purpose without the
express permission of SAP AG. The information contained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietary software components
of other software vendors.
Microsoft, Windows, Excel, Outlook, PowerPoint, Silverlight, and Visual Studio are registered trademarks of
Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z,
System z10, z10, z/VM, z/OS, OS/390, zEnterprise, PowerVM, Power Architecture, Power Systems,
POWER7, POWER6+, POWER6, POWER, PowerHA, pureScale, PowerPC, BladeCenter, System Storage,
Storwize, XIV, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, AIX, Intelligent Miner,
WebSphere, Tivoli, Informix, and Smarter Planet are trademarks or registered trademarks of IBM
Corporation.
Linux is the registered trademark of Linus Torvalds in the United States and other countries.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are trademarks or registered trademarks of Adobe
Systems Incorporated in the United States and other countries.
Oracle and Java are registered trademarks of Oracle and its affiliates.
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or
registered trademarks of Citrix Systems Inc.
HTML, XML, XHTML, and W3C are trademarks or registered trademarks of W3C®, World Wide Web
Consortium, Massachusetts Institute of Technology.
Apple, App Store, iBooks, iPad, iPhone, iPhoto, iPod, iTunes, Multi-Touch, Objective-C, Retina, Safari, Siri,
and Xcode are trademarks or registered trademarks of Apple Inc.
IOS is a registered trademark of Cisco Systems Inc.
RIM, BlackBerry, BBM, BlackBerry Curve, BlackBerry Bold, BlackBerry Pearl, BlackBerry Torch, BlackBerry
Storm, BlackBerry Storm2, BlackBerry PlayBook, and BlackBerry App World are trademarks or registered
trademarks of Research in Motion Limited.
Google App Engine, Google Apps, Google Checkout, Google Data API, Google Maps, Google Mobile Ads,
Google Mobile Updater, Google Mobile, Google Store, Google Sync, Google Updater, Google Voice, Google
Mail, Gmail, YouTube, Dalvik and Android are trademarks or registered trademarks of Google Inc.
INTERMEC is a registered trademark of Intermec Technologies Corporation.
Wi-Fi is a registered trademark of Wi-Fi Alliance.
Bluetooth is a registered trademark of Bluetooth SIG Inc.
Motorola is a registered trademark of Motorola Trademark Holdings LLC.
Computop is a registered trademark of Computop Wirtschaftsinformatik GmbH.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer, StreamWork,
SAP HANA, and other SAP products and services mentioned herein as well as their respective logos are
trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web
Intelligence, Xcelsius, and other Business Objects products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of Business Objects Software Ltd. Business
Objects is an SAP company.
Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase products and
services mentioned herein as well as their respective logos are trademarks or registered trademarks of
Sybase Inc. Sybase is an SAP company.

© 2012 SAP AG. All rights reserved.


SAP Sourcing 9.0 Scripting and Workflow Guide 38

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.

© 2012 SAP AG. All rights reserved.

Potrebbero piacerti anche