Scripting and Workflow Guide
SAP Sourcing
Target Audience
System administrators
Technology consultants
PUBLIC
Document version: 2.00 – May 2011
© Copyright 2013 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, Outlook, and PowerPoint are registered
trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex,
MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries,
xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity,
Tivoli, Informix, i5/OS, POWER, POWER5, OpenPower and
PowerPC are trademarks or registered trademarks of IBM Corporation.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either
trademarks or registered trademarks of Adobe Systems Incorporated in
the United States and/or other countries.
Oracle is a registered trademark of Oracle Corporation.
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.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used
under license for technology invented and implemented by Netscape.
MaxDB is a trademark of MySQL AB, Sweden.
SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, 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 in several other countries all over the world. 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.
SAP Library document classification: PUBLIC
Disclaimer
Some components of this product are based on Java™. Any
code change in these components may cause unpredictable
and severe malfunctions and is therefore expressively
prohibited, as is any decompilation of these components.
Any Java™ Source Code delivered with this product is
only to be used by SAP’s Support Services and may not be
modified or altered in any way.
Documentation in the SAP Service Marketplace
You can find this documentation at the following address:
http://service.sap.com/instguides
SAP AG
Dietmar-Hopp-Allee 16 69190 Walldorf Germany T +49/18 05/34 34 24 F +49/18 05/34 34 20 www.sap.com
Terms for Included Open
Source Software
This SAP software contains also the third party open
source software products listed below. Please note that for
these third party products the following special terms and
conditions shall apply.
1. This software was developed using ANTLR.
2. gSOAP
Part of the software embedded in this product is gSOAP
software. Portions created by gSOAP are Copyright
(C) 2001-2004 Robert A. van Engelen, Genivia inc. All
Rights Reserved.
THE SOFTWARE IN THIS PRODUCT WAS IN PART
PROVIDED BY GENIVIA INC AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL THE AUTHOR BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
3. SAP License Agreement for STLport
SAP License Agreement for STLPort between
SAP Aktiengesellschaft
Systems, Applications, Products in Data Processing
Neurottstrasse 16
69190 Walldorf, Germany
(hereinafter: SAP)
and
you
(hereinafter: Customer)
a) Subject Matter of the Agreement
A) SAP grants Customer a non-exclusive,
non-transferrable, royalty-free license to use
the STLport.org C++ library (STLport) and its
documentation without fee.
B) By downloading, using, or copying STLport or
any portion thereof Customer agrees to abide
by the intellectual property laws, and to all of
the terms and conditions of this Agreement.
C) The Customer may distribute binaries compiled
with STLport (whether original or modified)
without any royalties or restrictions.
D) Customer shall maintain the following
copyright and permissions notices on STLport
sources and its documentation unchanged:
Copyright 2001 SAP AG
E) The Customer may distribute original or
modified STLport sources, provided that:
o The conditions indicated in the above
permissions notice are met;
o The following copyright notices are retained
when present, and conditions provided in
accompanying permission notices are met:
Coypright 1994 Hewlett-Packard
Company
Copyright 1996,97 Silicon Graphics
Computer Systems Inc.
Copyright 1997 Moscow Center for
SPARC Technology.
Copyright 1999,2000 Boris Fomitchev
Copyright 2001 SAP AG
Permission to use, copy, modify, distribute and
sell this software and its documentation for
any purposes is hereby granted without fee,
provided that the above copyright notice appear
in all copies and that both that copyright notice
and this permission notice appear in supporting
documentation. Hewlett-Packard Company
makes no representations about the suitability
of this software for any purpose. It is provided
“as is” without express or implied warranty.
Permission to use, copy, modify, distribute and
sell this software and its documentation for any
purpose is hereby granted without fee, provided
that the above copyright notice appear in all
copies and that both that copyright notice and
this permission notice appear in supporting
documentation. Silicon Graphics makes no
representations about the suitability of this
software for any purpose. It is provided “as is”
without express or implied warranty.
Permission to use, copy, modify, distribute and
sell this software and its documentation for
any purposes is hereby granted without fee,
provided that the above copyright notice appear
in all copies and that both that copyright notice
and this permission notice appear in supporting
documentation. Moscow Center for SPARC
makes no representations about the suitability
of this software for any purpose. It is provided
“as is” without express or implied warranty.
Boris Fomitchev makes no representations
about the suitability of this software for any
purpose. This material is provided "as is", with
absolutely no warranty expressed or implied.
Any use is at your own risk. Permission to
use or copy this software for any purpose is
hereby granted without fee, provided the above
notices are retained on all copies. Permission
to modify the code and to distribute modified
code is granted, provided the above notices
are retained, and a notice that the code was
modified is included with the above copyright
notice.
Permission to use, copy, modify, distribute
and sell this software and its documentation
for any purposes is hereby granted without
fee, provided that the above copyright notice
appear in all copies and that both that copyright
notice and this permission notice appear in
supporting documentation. SAP makes no
representations about the suitability of this
software for any purpose. It is provided with a
limited warranty and liability as set forth in the
License Agreement distributed with this copy.
SAP offers this liability and warranty obligations
only towards its customers and only referring
to its modifications.
b) Support and Maintenance
SAP does not provide software maintenance for the
STLport. Software maintenance of the STLport
therefore shall be not included.
All other services shall be charged according to the
rates for services quoted in the SAP List of Prices
and Conditions and shall be subject to a separate
contract.
c) Exclusion of warranty
As the STLport is transferred to the Customer on a
loan basis and free of charge, SAP cannot guarantee
that the STLport is error-free, without material
defects or suitable for a specific application under
third-party rights. Technical data, sales brochures,
advertising text and quality descriptions produced
by SAP do not indicate any assurance of particular
attributes.
d) Limited Liability
A) Irrespective of the legal reasons, SAP shall only
be liable for damage, including unauthorized
operation, if this (i) can be compensated under
the Product Liability Act or (ii) if caused due to
gross negligence or intent by SAP or (iii) if based
on the failure of a guaranteed attribute.
B) If SAP is liable for gross negligence or intent
caused by employees who are neither agents or
managerial employees of SAP, the total liability
for such damage and a maximum limit on the
scope of any such damage shall depend on
the extent to which its occurrence ought to
have anticipated by SAP when concluding the
contract, due to the circumstances known to
it at that point in time representing a typical
transfer of the software.
C) In the case of Art. 4.2 above, SAP shall not
be liable for indirect damage, consequential
damage caused by a defect or lost profit.
D) SAP and the Customer agree that the typical
foreseeable extent of damage shall under no
circumstances exceed EUR 5,000.
E) The Customer shall take adequate measures
for the protection of data and programs, in
particular by making backup copies at the
minimum intervals recommended by SAP. SAP
shall not be liable for the loss of data and its
recovery, notwithstanding the other limitations
of the present Art. 4 if this loss could have been
avoided by observing this obligation.
F) The exclusion or the limitation of claims in
accordance with the present Art. 4 includes
claims against employees or agents of SAP.
4. Adobe Document Services
Adobe, the Adobe logo, Acrobat, PostScript, and Reader
are either registered trademarks or trademarks of
Adobe Systems Incorporated in the United States and
/ or other countries. For information on Third Party
software delivered with Adobe document services and
Adobe LiveCycle Designer, see SAP Note 854621.
Typographic Conventions
Type Style Description
Example Text Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options.
Cross-references to other documentation
Example text Emphasized words or phrases in body text, graphic titles, and table titles
EXAMPLE TEXT Technical names of system objects. These include report names, program names, transaction codes, table names, and key concepts of a programming language when they are surrounded by body text, for example, SELECT and INCLUDE.
Example text Output on the screen. This includes file and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools.
Example text Exact user entry. These are words or characters that you enter in the system exactly as they appear in the documentation.
<Example
text> Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system.
EXAMPLE TEXT Keys on the keyboard, for
example, F2 or ENTER.
Icons
Icon Meaning
Caution
Example
Note
Recommendation
Syntax
Additional icons are used in SAP Library documentation to help you identify different types of information at a glance. For more information, see
Help on Help General Information Classes and Information Classes for Business Information Warehouse on the first page of any version of SAP Library.
7
Contents
1 Introduction ......................................................................................... 9
1.1 Intended Audience and Assumptions .................................................. 9
1.2 Guide Layout and Conventions ............................................................ 9
1.3 Terminology ............................................................................................ 9
2 Scripting ............................................................................................. 11
2.1 Scripting Business Documents .......................................................... 11 Script Context ...................................................................................................................... 11 Document Life Cycle ............................................................................................................ 12 Import Life Cycle .................................................................................................................. 13 Additional Script Control ...................................................................................................... 14 Collections (Subordinate Classes) ....................................................................................... 15 System-Set Variables .......................................................................................................... 16 System-Provided Methods ................................................................................................... 17
2.2 Authoring a Script ................................................................................ 18
2.3 BeanShell Versus Java Styles ............................................................ 18
2.4 Handling Exceptions ............................................................................ 18
2.5 Localized Resources and Exceptions ................................................ 20
2.6 Use of Internal APIs ............................................................................. 20
2.7 Using Scripting to Assist with Mass Changes................................... 21
2.8 IBean Management ............................................................................... 21
2.9 Scripting Examples .............................................................................. 22 Logging Exceptions .............................................................................................................. 22 Independent Field Check ..................................................................................................... 23 Dependent Field Check ....................................................................................................... 24 Set Default Value ................................................................................................................. 24 Iterating Over a Collection (Exception Chaining) ................................................................. 25 Adding to a Collection .......................................................................................................... 25 Dealing with Value Lists ....................................................................................................... 25 SAP Sourcing Types ............................................................................................................ 26 Top-Level Category Check .................................................................................................. 26 Prevent Changing from or to a Status ................................................................................. 27
3 Workflow ............................................................................................ 29
3.1 Workflow-Enabled Business Documents ........................................... 29
3.2 Workflow System Functionality .......................................................... 29
3.3 Overview of the XPDL File ................................................................... 29
3.4 Workflow Definitions ............................................................................ 30
3.5 Workflow Development Cycle ............................................................. 31
3.6 Scriptable Functionality ....................................................................... 31
3.7 Scripting Workflows ............................................................................. 31 Pre-Phase Change Scripts .................................................................................................. 31 XPDL Embedded Scripts ..................................................................................................... 31 System-Set Variables .......................................................................................................... 33 System-Provided Methods ................................................................................................... 34 Scripting Transitions ............................................................................................................ 34
SAP Sourcing Scripting and Workflow Guide
8
Special Considerations for Contract Documents ................................................................. 36 Workflow Metadata .............................................................................................................. 36 Ad-Hoc Approvals ................................................................................................................ 37
3.8 Configuring Supplier Workflow Management .................................... 37 Creating a Workflow Definition ............................................................................................ 37 Creating a Supplier Configurable Phase Definition ............................................................. 37 Creating or Editing a Supplier Type ..................................................................................... 38 Creating a Supplier Field Access Definition (Optional) ........................................................ 39 Configuring Security Templates ........................................................................................... 40 Assigning a Supplier Type to a Supplier .............................................................................. 40 Configuring Supplier-Side UI Mapping ................................................................................ 40 Configuring the System to Use a Supplier Approval Process Without Workflow ................ 41
3.9 Workflow Examples ............................................................................. 41 Prescript ............................................................................................................................... 41 Postscript ............................................................................................................................. 42 PreCancelScript ................................................................................................................... 42 Change Approver ................................................................................................................. 43 Getting the Submitter of a Workflow .................................................................................... 43
Appendix A: Scripting Guidelines ...................................................... 44
Design ......................................................................................................... 44
Writing Scripts ............................................................................................ 44
Exceptions .................................................................................................. 44
General ........................................................................................................ 44
Appendix B: Utility Classes ................................................................ 45
1 Introduction
9
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.
1 Introduction
10
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.
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.
2 Scripting
11
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
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 contect. The following table summarizes the available scripting contexts.
Context Description
Field A script at the field level executes when the field changes or when the document is fully validated, for example, when the field is first saved after creation, 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.*
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 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 A document script executes as dictated by the target lifecycle.
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.
2 Scripting
12
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.
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
Loaded Point at which the document is loaded and not editable, for example, when selecting a project from the My Projects picker. A number of internal processes invoke this event, such as the daemon responsible for pushing document security template changes.
Of limited use, as the document is not changeable at the time it is loaded.
Extreme care should be exercised, as scripting this event can cause performance issues and other undesirable effects.
Created Point at which the class is instantiated as new
Ideal time to provide alternative defaults. Does not execute when the Create from Template or Document Duplicate actions are performed.
Duplicated Creation of a document using the Duplicate button or Create from Template option.
As with the Created event, this is a good opportunity to provide alternative defaults.
Pre Phase Change
On business documents that support configurable phase definitions, a script that executes prior to the phase change. RFx and Auction phases are not included.
Scripts that raise exceptions in this context stop the phase change from occurring. In addition, the document is fully validated prior to this script, which includes the execution of any scripts.
2 Scripting
13
Event Description Notes/Examples
Post Phase Change
Script that executes immediately after the phase change
As the phase change has already occurred and the document is fully validated, no additional validation should be done at this time and no changes should be made to the document.
Pre Publish to ERP
On business documents that support publishing to ERP, a script that executes prior to the publishing.
The business document is saved prior to the execution of this script. Any exceptions that are raised in this context stop the publishing from occurring.
Validated
Document validation scripts run when the document changes and the user saves the document, or another action is taken, such as a phase change, that invokes a validation.
Useful for field validations that are dependent on each other. This is the final point at which changes can be made safely by a script.
Saved Once the documentation passes validation and is stored in the database, this script executes.
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 business document affect the post-saved version and cause confusion for users.
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 scripting at the beginning of file processing. There
None Of limited use, as no record data is available.
2 Scripting
14
Event Description Data Context Notes/Examples
is no record or ibean data available. Xan be used to validate environmental variables, for example.
Pre-Process Row Allows access to inbound data before the iBean has been created.
Record
Should Process Row
Gives the opportunity to reject the import of a particular row.
Record The script must return a Boolean object .
Process Row Gives the opportunity to manipulate the newly constructed iBean before it is saved.
iBean
Ok To Save Gives the opportunity to reject the save of a particular iBean
iBean The script must return a Boolean object.
Save Gives the opportunity to act on the iBean *after* it has been saved.
iBean Could be used to write out custom log information, or send custom notifications.
Final This is the mirror image of the Init event. Allows scripting after the import of the entire file has completed.
None
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 Context
Classes Supported
Instance Type Options are Document only, Template only, and Any.
All Classes that support templates
Document Type A list of defined document types for the selected class
All Classes that support types
2 Scripting
15
Limit Description Script Context
Classes Supported
Toolbar Script Visibility View Mode, Edit Mode, or View or Edit Mode. Controls what edit state the document can be in before the script is executable.
Toolbar scripts only
All top-level classes
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 Context
Class Target
(A) Collection Supplier CERTS
(B) Document CERTS (all lifecycle events)
(C) Field/Field Data Edit
CERTS (target field)
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.
2 Scripting
16
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”);
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
All All session Instance of IapiSessionConte
xtIfc for the current
user’s session
Document Duplicated otherDoc Reference to document that is being duplicated
Document Pre and Post Phase Changes
current_phase String representing 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-Phase Changes
other_phase String representing internal ID of target phase of document in Pre-Phase change script or previous phase in Post-Phase change script
2 Scripting
17
Context Event Variable Description
Document Pre- and Post-Phase Changes
phase_advancing
Boolean set to true if the phase change is forward
Field & Field Data Edit
field Reference to the IBeanFieldMdIfc
for field in question
Field & Field Data Edit
fieldValue Reference to value of 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
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, or test that a SAP Sourcing object, though not null, has some real value set.
Only works for Java String type and the following SAP Sourcing types: SimpeObjectRefenceIfc,
AmountIfc, PriceIfc,
AttachmentIfc,
EnumTypeIfc,
ResourceIfIfc,
SysDateIfc,
SysDatetimeIfc,
SysTimeIfc
getFieldValue() In Field and Field Data Edit scripts, returns the value of field
Not normally used, as variable
fieldValue accomplishes this
2 Scripting
18
Method Description Notes
setFieldValue(Object
object)
In Field and Field Data Edit
scripts, sets value of field to
specified value
createApplicationExcepti
on(String attr, msgid)
Creates an exception on specified attribute using specified localized resource
There is no real convenience in this method. See Scripting Examples (page 22) 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:
2 Scripting
19
Raise the exception and stop the script.
Validate the whole document and raise all at once (chaining exceptions).
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.
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.
2 Scripting
20
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.
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.
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).setExceptio
n(e).setLogMessage(“My script failed”));
throw new ApplicationException(session,
“custom.exception.error.id”);
}
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.
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”);
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.
2 Scripting
21
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).
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.UserAccountIBean
Ifc;
curr =
acct.getFieldMetadata(UserAccountIBeanIfc.sPROPID_CURRENC
Y).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);
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” );
2 Scripting
22
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(“[email protected]”);
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.
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.
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”);
2 Scripting
23
// 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).setExcep
tion(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).setExceptio
n(e.getRootException() ));
See Handling Exceptions (page 18) for further details on exception handling.
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(),
2 Scripting
24
"custom.invalid.term.period");
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”);
}
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);
// Set default currency
//
import
com.frictionless.api.usermgmt.masterdata.UserAccountIBean
Ifc;
curr =
acct.getFieldMetadata(UserAccountIBeanIfc.sPROPID_CURRENC
Y).get(acct);
doc.setCurrency(curr);
2 Scripting
25
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();
}
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);
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.
2 Scripting
26
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(STAT
US_COMPLETED) {
// … DO SOMETHING …
}
// DON’T DO – This *will* break at some point
if(hasValue(fieldValue) @and
fieldValue.getDisplayName().equals(STATUS_COMPLETED)) {
// … DO SOMETHING …
}
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()));
...
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;
}
2 Scripting
27
intCatHome = IBeanHomeLocator.lookup(session,
fieldValue);
categoryIBean = intCatHome.find(intCat);
if(!hasValue(categoryIBean.getParentObjRef()) ) {
throw
doc.createApplicationException(field.getAttributeId(),
"custom.top_level_commodity_not_allowed");
}
Prevent Changing from or to a Status
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.frictionless.api.usermgmt.masterdata.GroupIBeanHomeIf
c;
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)
2 Scripting
28
@and IBeanHomeLocator.lookup(session,
newFieldValue).find(newFieldValue).getDisplayName().equal
s("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("Com
pleted")
@and !fieldValue.equals(newFieldValue)) {
throw doc.createApplicationException("STATUS",
"custom.cannot.change.from.completed");
}
3 Workflow
29
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
Suppliers
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.
3 Workflow
30
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.
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 Workflow
31
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.
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
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.
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
Postscript 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 automatically.
PreCancelScript 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,
move the document back to a prior phase.
3 Workflow
32
TransitionCondition 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 (page 34) 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.
Extended Attribute Description
LocalizedDescription A string that represents a resource ID
(bundle$resource_id) in SAP Sourcing, such as
custom$workflow.desc. This description is
added to the approver’s notification email.
ApprovalActivity 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. Omit this attribute or set it to TRUE.
Duration The unit of duration expected for this activity. This is stored in the workflow history and may be a useful metric for analysis.
DurationUnit M,D,Y. The unit of measure for the Duration attribute.
LocalizedInstructions A string that represents a resource ID
(bundle$resource_id) in SAP Sourcing, such as
custom$workflow.instr. These instructions are
added to the approver’s notification email.
The following figure shows a typical activity’s extended attributes:
3 Workflow
33
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 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 37) for ways to access information about the actual submitter.
nativeId String representing XPDL attribute ID for current activity
nativeName String representing XPDL attribute Name of current activity
workItem Reference to current step in approval process and only available in PostScript activity
3 Workflow
34
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 representing the current status of the activity. Used only in transitions.
The values returned are adapted from the ApprovalStatusEnumType
class.
addApprover(principal) Adds the specified principal to the list of approvers. The principal must be an object reference to a group or a user (see Workflow Examples on page 37).
principle must be an instance of
an ObjectReferenceIfc that
refers to GroupIBeanIfc, or UserAccountIBeanIfc
addApprover(principal, rule) 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 example in Workflow Examples for details).
rule is an instance of CollaboratorApprovalRule
Type
cancelProcess(comment) Provides a way of canceling the workflow process in-script. This results in execution of the
PreCancelScript.
comment is a Java string. That string is stored in the workflow history of the document.
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.
3 Workflow
35
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 Workflow
36
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.
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 agreement
0 100000 Managers
Buyer Recurring agreement
0 100000 Supervisors
Manager NDA 0 0 Legal
3 Workflow
37
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 37) for a similar scenario to this one.
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.8 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.
Creating a Workflow Definition 1. Navigate to Setup Platform 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. Chose 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.
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 Platform 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.
3 Workflow
38
8. Save your entries. 9. Create additional Supplier Configurable Phase Definitions as needed.
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 Platform 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 XPDL file, 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.
3 Workflow
39
4. On the Type page, assign a Supplier Configurable Phase Definition to the Supplier Type.
5. Save your entries.
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 Platform 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 Error! Reference source not found. 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 Workflow
40
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.
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.
Note: When a supplier is created via workflow, the supplier type that was used for creation is assigned to the supplier.
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.
3 Workflow
41
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.
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.9 Workflow Examples
Prescript
Scenario - IIterate 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;
3 Workflow
42
import
com.frictionless.api.doc.collaboration.CollaboratorApprov
alRuleType;
for(member : iterator) {
if(requestType.equals(member.get("REQUEST_TYPE")) @and
(cpSubGroup.equals(member.get("CP_SUB_GRP"))) ) {
if(projectContractValue.compareTo(member.get("FROM_VAL
UE"))
@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");
}
Postscript
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,"FundingReq
uest");
}
PreCancelScript
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 Workflow
43
Change Approver
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.getAcc
ountObjectReference());
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();
Appendix A: Scripting Guidelines
44
Appendix A: Scripting Guidelines
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.
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.
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.
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.
Appendix B: Utility Classes
45
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 initSystemServices() which should not be used.
Provides functionality to access system properties 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