Sunteți pe pagina 1din 43

SAP Sourcing Release 10.

Scripting and Workflow Guide

March 2014

2014 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............................................................................................................... 12
2.2 Authoring a Script ................................................................................................................................. 12
2.3 BeanShell Versus Java Styles .............................................................................................................. 13
2.4 Handling Exceptions ............................................................................................................................. 13
2.5 Localized Resources and Exceptions ................................................................................................... 15
2.6 Use of Internal APIs .............................................................................................................................. 15
2.7 Using Scripting to Assist with Mass Changes ...................................................................................... 15
2.8 IBean Management............................................................................................................................... 16
2.9 Scripting Examples ............................................................................................................................... 17
2.9.1 Logging Exceptions ......................................................................................................................... 17
2.9.2 Independent Field Check ................................................................................................................. 19
2.9.3 Dependent Field Check ................................................................................................................... 19
2.9.4 Set Default Value ............................................................................................................................. 19
2.9.5 Iterating Over a Collection (Exception Chaining)............................................................................. 20
2.9.6 Adding to a Collection ...................................................................................................................... 20
2.9.7 Dealing with Value Lists ................................................................................................................... 21
2.9.8 SAP Sourcing Types ........................................................................................................................ 21
2.9.9 Top-Level Category Check .............................................................................................................. 22
2.9.10 Prevent Changing from or to a Status ............................................................................................. 22
2.9.11 Explicitly Called Scripts .................................................................................................................... 23
2.10 Troubleshooting .................................................................................................................................. 24
2.10.1 Script Logging .................................................................................................................................. 24
2.10.2 Document-Related Scripts Report ................................................................................................... 24
3 Workflow .............................................................................................................................................. 26
3.1 Workflow-Enabled Business Documents .............................................................................................. 26

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 3

3.2 Workflow System Functionality ............................................................................................................. 27


3.3 Workflow Definitions ............................................................................................................................. 27
3.3.1 Creating and Changing a Workflow Process Template ................................................................... 27
3.4 Workflow Delegation ............................................................................................................................. 27
3.5 Scriptable Functionality ......................................................................................................................... 28
3.6 Scripting Workflows .............................................................................................................................. 28
3.6.1 Pre-Phase Change Scripts .............................................................................................................. 28
3.6.2 Embedded Scripts ........................................................................................................................... 28
3.6.3 General Activity Attributes ............................................................................................................... 29
3.6.4 System-Set Variables ...................................................................................................................... 30
3.6.5 System-Provided Methods............................................................................................................... 30
3.6.6 Special Considerations for Contract Documents ............................................................................. 31
3.6.7 Workflow Metadata .......................................................................................................................... 31
3.6.8 Ad-Hoc Approvals ............................................................................................................................ 32
3.7 Configuring Supplier Workflow Management ....................................................................................... 32
3.7.1 Creating a Workflow Definition ........................................................................................................ 33
3.7.2 Creating a Supplier Configurable Phase Definition ......................................................................... 33
3.7.3 Creating or Editing a Supplier Type ................................................................................................. 34
3.7.4 Creating a Supplier Field Access Definition (Optional) ................................................................... 35
3.7.5 Configuring Security Templates ...................................................................................................... 35
3.7.6 Assigning a Supplier Type to a Supplier .......................................................................................... 35
3.7.7 Configuring Supplier-Side UI Mapping ............................................................................................ 36
3.7.8 Configuring the System to Use a Supplier Approval Process Without Workflow ............................ 36
3.8 Workflow Examples .............................................................................................................................. 36
3.8.1 Prescript ........................................................................................................................................... 36
3.8.2 Postscript ......................................................................................................................................... 37
3.8.3 PreCancelScript ............................................................................................................................... 38
3.8.4 Change Approver ............................................................................................................................. 38
3.8.5 Getting the Submitter of a Workflow ................................................................................................ 38
Appendix A: Scripting Guidelines ............................................................................................................... 40
A.1 Design ....................................................................................................................................................... 40
A.2 Writing Scripts ........................................................................................................................................... 40
A.3 Exceptions ................................................................................................................................................. 40
A.4 General ...................................................................................................................................................... 40
Appendix B: Utility Classes .......................................................................................................................... 41
Copyrights, Trademarks, and Disclaimers....................................................................................................... 42

2014 SAP AG. All rights reserved.


SAP Sourcing 10.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 BeanShell. 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.
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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 5

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.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

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.

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


Event

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 7

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.

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 Lifecycle Event 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

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 8

Event Description Notes/Examples

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.

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

Init The init hook allows None Of limited use, as no


scripting at the beginning record data is available.
of file processing. There
is no record or ibean
data available. Xan be
used to validate
environmental variables,
for example.
Pre-Process Row Allows access to inbound Record
data before the iBean
has been created.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 9

Event Description Data Context Notes/Examples

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.

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 10

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.
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

All All doc Reference to the


current document
being scripted, also
called an IBean

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 11

Context Event Variable Description

All All session Instance of


IapiSessionConte
xtIfc for the current
users session

Document Duplicated otherDoc Reference to


document that is
being duplicated

Document Pre and Post current_phase String representing


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

Document Pre- and Post- other_phase String representing


Phase Changes internal ID of target
phase of document in
Pre-Phase change
script or previous
phase in Post-Phase
change script

Document Pre- and Post- phase_advancing Boolean set to true if


Phase Changes the phase change is
forward

Field & Field Data field Reference to the


Edit IBeanFieldMdIfc
for field in question

Field & Field Data fieldValue Reference to value of


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

Field Data Edit newFieldValue Reference to new


value

Collection collection Reference to


collection being
scripted

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 12

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. 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

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 17) 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
developers 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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 13

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

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 14

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

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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 15

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

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.sap.odp.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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 16

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 IBeans 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);
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:

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 17

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

Note
Standard logging is available for troubleshooting scripts. See Troubleshooting for details.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 18

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 for further details on exception handling.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 19

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 creators 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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 20

//
user = session.getAccount().getAccountObjectReference();
acct = IBeanHomeLocator.lookup(session, user).find(user);

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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 21

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

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

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

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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 22

newLink = doc.getDocumentLinkList().create();
newLink.setDisplayName( rfx.getDisplayName() );
newLink.setLinkDate(TypeFactory.createSysDatetime(new
java.util.Date()));
...

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


//

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 23

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]);
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. It
can also be used to support Web Services script-based services.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 24

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.

2.10.2 Document-Related Scripts Report


For a given Sourcing document, the Document-Related Scripts report provides details about each active
script, including scripting hook type (context), display name, instance type, doc type, and target. It indicates
the sequence of the script execution relative to the document lifecycle. It provides information about related
subordinate objects and scripts associated with them.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 25

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 26

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.

3.1 Workflow-Enabled Business Documents


The following business documents are workflow enabled:
Projects
Contract documents (under master agreements and agreements)
Suppliers
User-defined business documents 1 through 5
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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 27

3.2 Workflow System Functionality


The system functionality relating to workflow processing generally should not be changed 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 Workflow Definitions


The Workflow Definition is the SAP Sourcing document that is associated with the workflow process defined
in the workflow schema file. Besides the information in the schema file, the workflow process template
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.3.1 Creating and Changing a Workflow Process Template


A workflow process template is 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.
A workflow process template can be saved as a draft version until complete. When the workflow is ready for
testing, the workflow process template can be published for use by new workflow activities, using the same
workflow definition. The Current Workflow Processes report is a tool used to delete failed workflow
processes and allow repeat testing.

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.

3.4 Workflow Delegation


Using delegation, workflow items assigned to one user can be reassigned to another user. Any workflow
items of the specified type assigned to you will be processed instead by the user you specify. For example, if
you delegate projects to another user, all projects assigned to you for approval will be sent to that user.
Delegation functionality can prevent potential delays in the workflow process when you are unavailable,
because your workflow items are sent for processing to an available user.
Enabling workflow delegation for a user for a particular business document class (for example, Contract
Documents) adds the delegated user as an Approver collaborator to all documents of that class, and sends
out e-mail notifications to the related users. The active work items are updated so that the delegated user
becomes the active approver, instead of the original user. While the original user is still a collaborator on the
document, they are not able to process the workflow approval while delegation is enabled. Once the
delegated user approves or rejects the work item, the document is again updated to set both the original
user and delegated user collaborator assignments to have the Inactive Approver Role as set in the relevant
Workflow Definition.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 28

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.

3.5 Scriptable Functionality


Because the core workflow functionality is immutable, the most common use 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. Another use of scripting is to change the phase of a document.

3.6 Scripting Workflows


3.6.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.6.2 Embedded Scripts


Three types of scripts can be assigned to each activity in the workflow process, described in the following
table. As with other scripting, SAP recommends that you use an external editor to create the scripts, and
paste them into the appropriate Prescript, Postscript, or PreCancelScript field.

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

Adds required approvers to the activity it is associated with.


Prescript
You can add a default prescript to all approval activities and
modify or delete individual prescripts as needed.

Performs any actions that might be needed after an activity is


Postscript 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 automatically.

When a script is canceled via the Current Workflow Processes


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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 29

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.

3.6.3 General Activity Attributes


In addition to these scripts, there are informational attributes that are optional, but are used in the workflow
history or general email notifications to approvers. Click anywhere in the step box (other than on the script
icons) to display the Attribute dialog box and general activity attributes.

Attribute Description

Approval The final activity must be a non-approval activity,


and all other activities are approval activities by
default. During an approval activity, the business
document is locked until approved, rejected, or
cancelled by an approver collaborator. During a non-
approval activity, all associated scripts are executed
before either advancing to the next available activity,
or for the final activity completing the workflow
process and unlocking the document.

Activity ID Required field. An internal identifier for each


workflow activity. Each Activity ID must be a unique
alphanumeric value formatted with underscores and
periods.

Activity Name Required field. A string that is a non-localized name


for each workflow activity.

Localized Activity Name The localized name for a workflow activity.

Activity Description A string that represents a resource ID


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

Activity Instruction A string that represents a resource ID


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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 30

Attribute Description

Duration The unit of duration expected for this activity. This is


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

Duration Unit Month, Day, or Year. (M,D,Y.) The unit of measure


for the Duration attribute.

3.6.4 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

session An instance of IapiSessionContextIfc for the


current users 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
submitter.

nativeId String representing the attribute ID for current


activity

nativeName String representing the attribute Name of current


activity

workItem Reference to current step in approval process and


only available in PostScript activity

3.6.5 System-Provided Methods


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

Method Description Notes

getApprovalStatus() Returns an int value The values returned are adapted


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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 31

Method Description Notes

addApprover(principal) Adds the specified principal to principle must be an instance of


the list of approvers. The an ObjectReferenceIfc that
principal must be an object refers to GroupIBeanIfc, or
reference to a group or a user UserAccountIBeanIfc
(see Workflow Examples for
details).

addApprover(principal, rule) Overloaded variant of the rule is an instance of


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

cancelProcess(comment) Provides a way of canceling the comment is a Java string. That


workflow process in-script. This string is stored in the workflow
results in execution of the history of the document.
PreCancelScript.

3.6.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.
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.

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.

3.6.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 workflow process and scripting knowledge. The

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 32

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.6.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.

3.7 Configuring Supplier Workflow Management


SAP Sourcing provides a default supplier type that is assigned to all suppliers in the system during upgrade.
This type contains no configured supplier phase definitions, which means that by default, supplier workflow
management is disabled.
To enable supplier workflow management, do the following:
1. Create Workflow Definitions.
2. Create Supplier Configurable Phase Definitions.
3. Create or Modify the Supplier Type.
4. Create a Supplier Field Access Definition (optional).
5. Configure Security Templates.
6. Assign Supplier Types to Suppliers.
7. Configure sell-side UI mapping.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 33

3.7.1 Creating a Workflow Definition


1. Navigate to Setup System Setup Workflow Workflow Definitions.
2. On the Workflow Definitions List page, choose New.
3. On the Workflow Definition Summary page, enter workflow information. For details, see Field Help
for Workflow Definition Summary page in the Online Help.
4. Choose the Add New Version button to add a process template to the workflow definition. For
details, see Field Help for Process Template dialog box in the Online Help.
5. Save your entries.
6. Create additional Workflow Definitions as needed.

3.7.2 Creating a Supplier Configurable Phase Definition


Supplier phases determine the actions that can be performed in supplier registration and modification
requests.
To create a supplier configurable phase definition:
1. Navigate to Setup Document Setup Supplier Configurable Phase Definition.
2. On the Supplier Configurable Phase Definition List page, choose New.
3. On the Header page, enter phase information. For details, see Field help for Supplier Configurable
Phase Definition Header page in the Online Help.
4. Choose Add to add phases to the definition.
5. In the dialog box that appears, select each phase to include in the phase definition and choose OK.
6. Choose each phase to edit phase information, including the sequence of phases in the workflow.
For details, see Field help for Supplier Configurable Phase Header page in the Online Help.
7. Optionally, assign workflow definitions and supplier field access.
8. Save your entries.
9. Create additional Supplier Configurable Phase Definitions as needed.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 34

3.7.3 Creating or Editing a Supplier Type


Supplier Types can be used to determine the workflow phase definition to enable in a supplier registration or
modification request. The Configurable Phase Definition field of the Supplier Type is responsible for defining
whether registration/modification requests will use workflow and which phases will have these requests.
If the Configurable Phase Definition field is empty, the supplier registration or modification request will not
have configured phases, and any supplier administrator will be able to approve or deny requests for this
type. To enable supplier workflow management, a supplier configurable phase definition must be assigned to
the supplier type.
SAP Sourcing provides one default supplier type. You can modify this type and create new ones.
1. Navigate to Setup Document Setup Suppliers Supplier Type.
2. On the Supplier Type List page, choose New to create a new type or select an existing type to
open it for editing.
3. On the Type page, enter information as needed. For details, see Field Help for Supplier Type
page in the Online Help.

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 35

3.7.4 Creating a Supplier Field Access Definition (Optional)


A Supplier Field Access Definition allows you to configure access rules for the approver for a specific phase.
To create a supplier field access definition:
1. Navigate to Setup Document Setup Suppliers Supplier Field Access Definition.
2. On the Supplier Field Access Definition List page, choose New.
3. On the UI page, enter information as needed. For details, see Supplier Field Access Definition in
the Online Help.
4. Save your entries.
5. Open an existing Supplier Configurable Phase Definition.
6. Choose Edit.
7. Select the phase for which you want to configure access rights for approvers. It must be an
approval phase.
8. Select a supplier field access definition to associate with this phase.
9. Save your changes.

3.7.5 Configuring Security Templates


Any Supplier Administrator can view and approve requests for supplier registrations and modifications that
do not have configured workflows. However, if new functionality is added, collaborator security must be in
place to automatically assign access rights to the functionality.
A document security template is a set of rules governing the way a sourcing document assigns collaborator
roles. You should configure collaborators, defined by role and user type, that are automatically added to a
registration and modification requests.

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:

The document owner must be any specified purchaser user.


The document creator (current user) must be added to the collaborator list with a role that allows the
user to view, edit, and change phases (such as Collaborator).
Supplier administrators should be included in the collaborator list so that they can view registration
and modification requests and manually complete them if automatic completion should fail.

3.7.6 Assigning a Supplier Type to a Supplier


During an upgrade, one default supplier type is created and assigned to all suppliers. It is used to recognize
phases for supplier modifications via workflow. The supplier type can be changed for any supplier.
To change the supplier type that is assigned to a supplier, do the following:

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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 36

Note
When a supplier is created via workflow, the supplier type that was used for creation is
assigned to the supplier

3.7.7 Configuring Supplier-Side UI Mapping


A Supplier Type can be mapped to any supplier-side self-registration form. In the Supplier Type, the Sell-
Side Supplier Registration UI Mapping allows you to configure mapping between the supplier type and self-
registration forms:

1. Open any Supplier Type.


2. Choose Edit.
3. Under Sell-Side Supplier Registration UI Mapping, choose Add to add a page that will be
mapped to this type.
4. Choose the value that corresponds to the Supplier Self-Registration URL you want to use.
For example, if you map a Supplier Type to UI 3, the registration link for this type will appear as
follows, including the final parameter:

/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.7.8 Configuring the System to Use a Supplier Approval Process


Without Workflow
After an upgrade, the SAP Sourcing system will use the supplier approval process without workflow. After
configuring a workflow approval process, if you decide to revert to the previous process, remove references
to the configurable phase definitions from all Supplier Types.

3.8 Workflow Examples


3.8.1 Prescript
The SAP Sourcing workflow editor allows you to create a default prescript for all approval activities, which
can be edited or deleted as necessary. The following example demonstrates scripting for a more complex
scenario.

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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 37

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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 38

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

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

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 39

processHome = IBeanHomeLocator.lookup(session,
WorkflowProcessIBeanHomeIfc.sHOME_NAME);
process = processHome.findByNativeId(nativeId);
return process.getCreator();

submitter = getSubmitter();

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 40

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 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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 41

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


IapiAccountLocator lookup() Provides different ways to
locate a user account
IapiDocumentLockManager All 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
approval.
IapiSystemUtilities All except Provides functionality to
initSystemServices() which access system properties
should not be used. and other information about
SAP Sourcing environment
IBeanHomeLocator lookup( ) Used to retrieve the home
interface for a specific class
Logger All Similar to the Log4j API,
provides access to SAP
Sourcing logging facility
TypeFactory All Common API to create SAP
Sourcing specific types

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 42

Copyrights, Trademarks, and Disclaimers


2014 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.

2014 SAP AG. All rights reserved.


SAP Sourcing 10.0 Scripting and Workflow Guide 43

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.

2014 SAP AG. All rights reserved.

S-ar putea să vă placă și