Scripting and Workflow Guide for SAP Sourcing

February 25, 2017 | Author: RahulSingh | Category: N/A
Share Embed Donate


Short Description

SAP Sourcing CLM scripting guide for version 9...

Description

SAP Sourcing Release 9.0

Scripting and Workflow Guide

September 2013

© 2013 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 ................................................................................................................................................ 5

2.1

Scripting Business Documents ............................................................................................................... 5

2.1.1

Script Context .................................................................................................................................... 5

2.1.2

Document Life Cycle .......................................................................................................................... 6

2.1.3

Import Life Cycle ................................................................................................................................ 7

2.1.4

Additional Script Control .................................................................................................................... 8

2.1.5

Collections (Subordinate Classes) .................................................................................................... 8

2.1.6

System-Set Variables ........................................................................................................................ 9

2.1.7

System-Provided Methods............................................................................................................... 11

2.2

Authoring a Script ................................................................................................................................. 11

2.3

BeanShell Versus Java Styles .............................................................................................................. 12

2.4

Handling Exceptions ............................................................................................................................. 12

2.5

Localized Resources and Exceptions ................................................................................................... 14

2.6

Use of Internal APIs .............................................................................................................................. 14

2.7

Using Scripting to Assist with Mass Changes ...................................................................................... 14

2.8

IBean Management............................................................................................................................... 15

2.9

Scripting Examples ............................................................................................................................... 16

2.9.1

Logging Exceptions ......................................................................................................................... 16

2.9.2

Independent Field Check ................................................................................................................. 18

2.9.3

Dependent Field Check ................................................................................................................... 18

2.9.4

Set Default Value ............................................................................................................................. 18

2.9.5

Iterating Over a Collection (Exception Chaining)............................................................................. 19

2.9.6

Adding to a Collection ...................................................................................................................... 19

2.9.7

Dealing with Value Lists ................................................................................................................... 19

2.9.8

SAP Sourcing Types ........................................................................................................................ 20

2.9.9

Top-Level Category Check .............................................................................................................. 21

2.9.10

Prevent Changing from or to a Status ............................................................................................. 21

2.9.11

Explicitly Called Scripts .................................................................................................................... 22

3

Workflow .............................................................................................................................................. 24

3.1

Workflow-Enabled Business Documents .............................................................................................. 24

3.2

Workflow System Functionality ............................................................................................................. 24

3.3

Overview of the XPDL File .................................................................................................................... 24

3.4

Workflow Definitions ............................................................................................................................. 25

3.5

Workflow Development Cycle ............................................................................................................... 25 © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

3

3.6

Scriptable Functionality ......................................................................................................................... 25

3.7

Scripting Workflows .............................................................................................................................. 26

3.7.1

Pre-Phase Change Scripts .............................................................................................................. 26

3.7.2

XPDL Embedded Scripts ................................................................................................................. 26

3.7.3

System-Set Variables ...................................................................................................................... 27

3.7.4

System-Provided Methods............................................................................................................... 28

3.7.5

Scripting Transitions ........................................................................................................................ 29

3.7.6

Special Considerations for Contract Documents ............................................................................. 30

3.7.7

Workflow Metadata .......................................................................................................................... 30

3.7.8

Ad-Hoc Approvals ............................................................................................................................ 31

3.8

Configuring Supplier Workflow Management ....................................................................................... 31

3.8.1

Creating a Workflow Definition ........................................................................................................ 31

3.8.2

Creating a Supplier Configurable Phase Definition ......................................................................... 32

3.8.3

Creating or Editing a Supplier Type ................................................................................................. 32

3.8.4

Creating a Supplier Field Access Definition (Optional) ................................................................... 33

3.8.5

Configuring Security Templates ...................................................................................................... 34

3.8.6

Assigning a Supplier Type to a Supplier .......................................................................................... 34

3.8.7

Configuring Supplier-Side UI Mapping ............................................................................................ 34

3.8.8

Configuring the System to Use a Supplier Approval Process Without Workflow ............................ 35

3.9

Workflow Examples .............................................................................................................................. 35

3.9.1

Prescript ........................................................................................................................................... 35

3.9.2

Postscript ......................................................................................................................................... 36

3.9.3

PreCancelScript ............................................................................................................................... 36

3.9.4

Change Approver ............................................................................................................................. 37

3.9.5

Getting the Submitter of a Workflow ................................................................................................ 37

Appendix A: Scripting Guidelines ............................................................................................................... 38 A.1 Design ....................................................................................................................................................... 38 A.2 Writing Scripts ........................................................................................................................................... 38 A.3 Exceptions ................................................................................................................................................. 38 A.4 General ...................................................................................................................................................... 38 Appendix B: Utility Classes .......................................................................................................................... 39 Copyrights, Trademarks, and Disclaimers....................................................................................................... 40

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

1

4

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. Extension collection: A collection that is user defined. Scripting interacts with these collections via the ExtensionCollectionIfc interface. Document (syn. Business Document, Object): An instance of the class. Extension member (syn. Member): An IBean that is part of a collection. Members of extension collections implement the ExtensionCollectionMemberIfc. Members of system collections return either an anonymous system type or a predefined member type. See the IAPI Documentation for detailed information. IBean: Any class that implements IBeanIfc. Every scriptable object is of this type. Import Record: A data structure containing the raw data from the inbound import file for one record. Home: A class that manages Lifecycle tasks related to its associated IBean. Every IBean has the Home interface. Top level (syn. Container): A class of objects that are by design not subordinate to another object. Projects, companies, master agreements, and agreements are all top-level objects. Script manager: The part of the underlying application that manages the script from creation to finish. Subordinate: A class or object that is part of a collection within a top-level class. Collaborators, extension collections, and RFx line items are all subordinate classes. System collection: A collection that is part of the SAP Sourcing class by design. Scripting accesses these collections via the parent class’s accessors. Members of these collections may have IAPI-defined types. 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. © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

5

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 Event

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.

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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

2.1.2

6

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.

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.

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.

Caution Extreme care should be exercised, as scripting this event can cause performance issues and other undesirable effects.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

7

Event

Description

Notes/Examples

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 postsaved 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 scripting at the beginning of file processing. There is no record or ibean data available. Xan be used to validate environmental variables, for example.

None

Of limited use, as no record data is available.

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

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

None

The script must return a Boolean object .

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

Event

Description

8

Data Context

Notes/Examples

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

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

2.1.5

Collections (Subordinate Classes)

There are two types of collections in SAP Sourcing: system and extension. Each row of data in a collection is called a member. Access to the collections is either via the provided accessor method in IAPI, or, for extension collections, via the getExtensionCollection(“logical name”) method. Collection members are also business documents in their own right, but are always wrapped in a parent document. As they are business documents, each supports the DLC events. During script definition, if the context selected is Collection, a list of collections for the selected class is shown. However, if the context selected is Document Lifecycle, the same collections are shown in the list of classes. This means that there are multiple ways of scripting collections. For example, given a Certifications collection with the attribute identifier of CERTS on the supplier object, a script can be written against the collection in the following ways: Scripting Context

Class

Target

(A) Collection

Supplier

CERTS

(B) Document

CERTS

(all lifecycle events)

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

Scripting Context

Class

Target

(C) Field/Field Data Edit

CERTS

(target field)

9



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

All

All

session

Instance of IapiSessionConte xtIfc for the current user’s session

Document

Duplicated

otherDoc

Reference to document that is being duplicated

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

10

Context

Event

Variable

Description

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

Document

Pre- and PostPhase 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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

2.1.7

11

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

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

2.2

There is no real convenience in this method. See Scripting Examples (page 16) for exception examples.

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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

12

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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

13

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

14

Note Comments related to authorship and script intentions should not be included in the script. They should be added to the Description field in the script definition.

2.5

Localized Resources and Exceptions

Because SAP Sourcing is designed as a localized application, strings of text are represented as localized resources. To specify the localized resource to be used for an exception, the methods for raising the exception are based on certain assumptions about the provided ID. Example In the following example, SAP Sourcing presents the error in the language of the current user’s session if the ID custom.exception.doc_desc.required is part of the bundle exception and of the type ERROR. The value of this resource ID must be translated to the relevant languages, or it is only displayed in the default language. doc.createApplicationException(“DOCUMENT_DESCRIPTION”, “custom.exception.doc_desc.required”);

2.6

Use of Internal APIs

SAP does not recommend the use of internal APIs for the following reasons: 

They are for internal use only.



They are undocumented.



They are subject to change without notice.



They are unsupported.

 They can result in corrupt data when used incorrectly. If there is a need for an object not covered in the IAPI JavaDoc, contact Customer Support using SAP Support Portal (http://service.sap.com). Example If an object does not expose an attribute, the value can still be obtained by using the field name of the property, as in the following example. // Need access to the CURRENCY on the User Account // acct = IBeanHomeLocator.lookup(session, user).find(user); import com.frictionless.api.usermgmt.masterdata.UserAccountIBeanIfc; curr = acct.getFieldMetadata(UserAccountIBeanIfc.sPROPID_CURRENCY).get(acct); If there is no property for the attribute you require, contact Customer Support using SAP Support Portal.

2.7

Using Scripting to Assist with Mass Changes

Using standard data importers over scriptable objects offers the developer a powerful tool to effect a global change. No new concepts are needed to create such scripts; all scripts defined for the object being imported execute just as they would if the object was created, or updated, from the UI. That is, for each record in the © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

15

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

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”); © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

16

... userHome.save(newUser); To duplicate a project, do the following: // Duplicate this project // newProject = doc.getIBeanHome().createFromAnother(doc);

2.9

Scripting Examples

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

2.9.1

Logging Exceptions

SAP Sourcing maintains log files during normal operations and developers can utilize these to store logging information from the script. As there is a performance impact with rigorous logging, scripts should log only in the following circumstances: 

For testing purposes (to be removed in the production script)

 To record errors that the end user cannot deal with, such as a third-party application being offline Do not log for every script if it is not necessary.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

17

The following example indicates one way to incorporate a logging model for a script that may log in greater volume due to its complexity: // Create a log message and set the method to be the script event // log = Logger.createLogMessage(session); log.setMethod(“ProjectPrePhase”); // Convenience method - Errors // logError(msg) { log.setLogMessage(error); Logger.error(log); } // Convenience method - Informational // logInfo(msg) { log.setLogMessage(error); Logger.info(msg); } /** Main script */ try { ... } catch(IOException e) { logError(“Could not write to the file, because of an IOError: ” + e.getMessage() ); return; } You can also log the exception and raise a more understandable exception, as follows: try { } catch(e) { Logger.error(Logger.createLogMessage(session).setException(e)); throw new ApplicationException (session, “helpful message ID”); } Occasionally, a lower-level SAP Sourcing function raises an exception without providing the underlying cause in the exception message. This can happen when saving the IBean. In such a case, substitute the following line: Logger.error(Logger.createLogMessage(session).setException(e.getRootEx ception() )); See Handling Exceptions (page 12) for further details on exception handling.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

2.9.2

18

Independent Field Check

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

2.9.3

Dependent Field Check

Scenario: FIELDA is anything at all, then FIELDB must be specified. Dependency checks require special consideration. Although it might seem that a field validation script on FIELDA would suffice, such a script only executes when FIELDA changes. If the script succeeds when the document is first saved, the user blanks FIELDB, and no error is raised because FIELDA did not change. This problem suggests the following rule: if validation is conditioned on anything outside of the field being validated, it must be part of the document validation script. // Document Validation Script, one field depends on another FIELDA = doc.getExtensionField(“FIELDA”).get(); FIELDB = doc.getExtensionField(“FIELDB”).get(); if(hasValue(FIELDA) @and !hasValue(FIELDB)) { throw doc.createApplicationException(“FIELDB”,”exception.value.is.required”) ; }

2.9.4

Set Default Value

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

19

// Set default currency // import com.sap.odp.api.usermgmt.masterdata.UserAccountIBeanIfc;

curr = acct.getFieldMetadata(UserAccountIBeanIfc.sPROPID_CURRENCY).get(acct); doc.setCurrency(curr);

2.9.5

Iterating Over a Collection (Exception Chaining)

Scenario: Check each row of a collection and if FIELDA is blank, raise an error on that row and cell. The following example provides a basic pattern for this common type of script (collection validation script): // The exception chain. Chain all exceptions to this one // exception = new ApplicationException(session); colln = doc.getExtensionCollection("my_collection"); if(colln.size() == 0) { return; } iter = colln.iterator(); for(member : iter) { feildA = member.get("FIELDA"); if(!hasValue(feildA) ) { exception.chainAtEnd(member.createApplicationException("FEILDA", "exception.feild.is.required")); } } // Handle the exceptions // if(exception.getChain() != null) { throw exception.getChain(); }

2.9.6

Adding to a Collection

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

2.9.7

Dealing with Value Lists

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

SAP Sourcing 9.0 Scripting and Workflow Guide

20

// Prints what the user sees print(lref.getDisplayName(session)); // Can sometimes print null print(lref.getDisplayName()); From a scripting perspective, an absolute reference is needed when checking values, so value lists should always be referenced by their internal identifier. Note In the UI for Value List Value Definition, this is labeled as Display Name, although this value is not displayed to the user. Value lists are often configured to give the display name the same value as the value list value’s default resource ID. However, if the value list values are longer than 40 characters, the display name must be abbreviated, so these values are not always identical. // Is the Project Status completed? // Field validation script on STATUS // Display Name, absolute ID, of the Completed status STATUS_COMPLETED = "Completed"; if(hasValue(fieldValue) @and IBeanHomeLocator.lookup(session, fieldValue).find(fieldValue).getDisplayName().equals(STATUS_COMPLETED) { // … DO SOMETHING … } // DON’T DO – This *will* break at some point if(hasValue(fieldValue) @and fieldValue.getDisplayName().equals(STATUS_COMPLETED)) { // … DO SOMETHING … }

2.9.8

SAP Sourcing Types

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

SAP Sourcing 9.0 Scripting and Workflow Guide

2.9.9

21

Top-Level Category Check

Scenario: Ensure that the selected category is not top level, to force the user to pick a category at the lower level. The following shows field validation on Internal Category field: // Check to make sure the Commodity (Int Cat) is not at the top level // if(!hasValue(fieldValue)) { return; } intCatHome = IBeanHomeLocator.lookup(session, fieldValue); categoryIBean = intCatHome.find(intCat); if(!hasValue(categoryIBean.getParentObjRef()) ) { throw doc.createApplicationException(field.getAttributeId(), "custom.top_level_commodity_not_allowed"); }

2.9.10

Prevent Changing from or to a Status

2.9.10.1

Scenario: Once a project is in a completed state, permit state changes to be performed only by users in a valid group.

The issue that arises from this script is that it executes during duplication. If the project being duplicated is completed, the script executes and stops the process. To prevent this problem, the project must be identified as new and allowed to be saved. The easiest way to accomplish this is to attempt to find the same IBean in the database. The following is the field data edit script on the Status field: // If this project is not in the database then return, // as it was just created and we have to be more // forgiving to allow the defaulting to take place // persistentDoc = doc.getIBeanHomeIfc().find(doc); if(persistentDoc == null) { return; } // Determine if the current user a member of admins // reportingGroups = new String[] { "sys_admins", "reg_admins", “buyer_managers"}; import com.sap.odp.api.usermgmt.masterdata.GroupIBeanHomeIfc; groupHome = IBeanHomeLocator.lookup(session, GroupIBeanHomeIfc.sHOME_NAME); isReportingUser = false; for (int i = 0; i < reportingGroups.length; i++) { currentGroup = groupHome.findGroup(reportingGroups[i]); © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

22

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

// If new status is in Completed Phase, make sure the // user is a member of one of the reporting groups // if (!isReportingUser @and hasValue(newFieldValue) @and IBeanHomeLocator.lookup(session, newFieldValue).find(newFieldValue).getDisplayName().equals("Completed" ) ) { throw doc.createApplicationException("STATUS", "custom.cannot.change.to.completed"); } // If the status is already in completed, make sure only reporting members can // change it // if (!isReportingUser @and hasValue(fieldValue) @and IBeanHomeLocator.lookup(session, fieldValue).find(fieldValue).getDisplayName().equals("Completed") @and !fieldValue.equals(newFieldValue)) { throw doc.createApplicationException("STATUS", "custom.cannot.change.from.completed"); }

2.9.11

Explicitly Called Scripts

Explicitly Called Scripts is a scripting object type that is not attached to a specific business document or context. It is a standalone script that can be executed from a scheduled task on a designated schedule. Example An example is a script that runs every night and checks if any master agreements are past expiration. If they are past the expiration date, the script changes the status of the master agreement to Expired. To create a new Explicitly Called Script: 1. Choose Setup  System Setup  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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

23

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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

3

24

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 utilizes a standardized format of the process definition XPDL 1.0. The XPDL file defines the steps the workflow must go through and the scripts for adding the required approvers at each step. To create and edit process definitions, use a third-party editor such as a text editor or specialized workflow editor that saves to XPDL 1.0 definitions. The process of creating and assigning workflow definitions is described in this guide. For more detailed information, see the SAP Sourcing Online Help.

3.1

Workflow-Enabled Business Documents

The following business documents are workflow enabled: 

Projects



Contract documents (under master agreements and agreements)



User-defined business documents 1 through 5

3.2

Workflow System Functionality

The system functionality relating to workflow processing is generally not changeable by scripting. System functionality refers to the following: 

Locking and unlocking of the document during the approval process



Processing approvals or rejections and changing the status of the approval process



Email notifications

3.3

Overview of the XPDL File

In the sample workflow below, the XPDL contains activities, represented by green or blue boxes, and transitions, represented by arrows. For the SAP Sourcing implementation, parallel approvals are not supported. Therefore, any activity must transition to the end or to the next activity. Blue activities are block activities and are required as the penultimate stage based on the XPDL specification. They are not treated differently by the workflow engine, but do act as a focal point for all transitions prior to the end of the process. The following sample 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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

25

In the following figure, there is only one activity:

3.4

Workflow Definitions

The Workflow Definition is the SAP Sourcing document that is associated with the workflow process defined in the XPDL file. Besides the information in the attached XPDL file, the workflow definition requires some additional information, as follows: 

The role for any approver added by the workflow



The role those approvers revert to post-workflow

 The process owner (this can usually remain set to the default) Approvers can be both individual users and groups. If groups are used, the collaborator role for approver must be configured to Allow Multiple.

3.5

Workflow Development Cycle

A typical development process employs an XPDL editor to create the XPDL file from an existing template. As with scripting, SAP recommends that you use a text editor to create the scripts before pasting them into the XPDL prescript and postscript. 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 © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

26

simple or extremely complex. Nevertheless, the result of the script is to add none, one, or more approvers to the document.

3.7

Scripting Workflows

3.7.1

Pre-Phase Change Scripts

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

3.7.2

XPDL Embedded Scripts

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

Description

Prescript

Adds required approvers to the activity it is associated with

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.

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 28) for more information.

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

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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

27

Extended Attribute

Description

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

System-Set Variables

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

Description

doc

Reference to current document under workflow

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

28

Variable

Description

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

System-Provided Methods

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

Description

Notes

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

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

29

Method

Description

Notes

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.

3.7.5

Scripting Transitions

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

30

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

Description

Pending

Activity is still pending user action.

Denied

Activity is rejected.

Approved

Activity is approved.

Completed

Non-approval activity was completed (not used).

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

3.7.6

Special Considerations for Contract Documents

Contract documents represent a special case for workflow. This business document is by nature subordinate to a parent master agreement or agreement (the container document). Although the phase changes and workflow history is tracked at the contract document level, the approvers are kept at the container level. When a script executes, the variable doc is the contract document IBean. If access is needed to the container, as is often the case, a reference to it can be obtained as follows: if(hasValue(doc.getParentIBean()) { parentContainer = doc.getParentIBean(); else { // Handle parent-not-loaded condtn here cancelProcess(“Parent Document not loaded. Contact a System Administrator.”); return; } There is a possibility that the contract document can be loaded without its container, so handling the null cases is mandatory.

3.7.7

Workflow Metadata

A common requirement is to be able to define the rules for the workflow in a dynamic way, such that changes to them do not require experience with the XPDL process and scripting knowledge. The recommended practice is to use extensions and extension collections to store this data. There are many potential business documents for such data. The following are some examples: 

Company



Organizational unit



Location



Document type © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

31

 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

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 31) for a similar scenario to this one.

3.7.8

Ad-Hoc Approvals

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

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. 2. 3. 4. 5. 6. 7.

3.8.1

Create Workflow Definitions. Create Supplier Configurable Phase Definitions. Create or Modify the Supplier Type. Create a Supplier Field Access Definition (optional). Configure Security Templates. Assign Supplier Types to Suppliers. Configure sell-side UI mapping.

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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

3.8.2

32

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: Navigate to Setup  Document Setup  Supplier Configurable Phase Definition. On the Supplier Configurable Phase Definition List page, choose New. On the Header page, enter phase information. For details, see Field help for Supplier Configurable Phase Definition Header page in the Online Help. Choose Add to add phases to the definition. In the dialog box that appears, select each phase to include in the phase definition and choose OK. 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. Optionally, assign workflow definitions and supplier field access. Save your entries. Create additional Supplier Configurable Phase Definitions as needed.

1. 2. 3. 4. 5. 6. 7. 8. 9.

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

33

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. 4. On the Type page, assign a Supplier Configurable Phase Definition to the Supplier Type. 5. Save your entries.

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

34

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.8.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.8.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. 2. 3. 4. 5.

Open the supplier for which you want to reassign the supplier type. Choose Edit. Choose Document Type and select a new supplier type. Choose OK. Save your changes.

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

3.8.7

Configuring Supplier-Side UI Mapping

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

Open any Supplier Type. Choose Edit. © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide 3. 4.

5.

35

Under Sell-Side Supplier Registration UI Mapping, choose Add to add a page that will be mapped to this type. 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 Save your entries.

Note A self-registration form can be assigned to only one supplier type. If a form does not have an assigned supplier type, the default supplier type will be used for registration.

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

Workflow Examples

3.9.1

Prescript

Scenario - Iterate over a collection which contains the approval rules. The main outcome from prescripts is to add an approver or not. In this case, a no match is not normal and the workflow can be canceled. This can vary depending on business requirements. // Get Document's Pertinent values. These attributes are all required // so no need to check for null // projectContractValue = doc.getExtensionField("PROJ_VALUE").get(); cpSubGroup = doc.getExtensionField("PUR_GRP").get(); requestType = doc.getExtensionField("REQUEST_TYPE").get(); // Get the workflow metadata // company = IBeanHomeLocator.lookup(session,doc.getCompanyRef() ).find(doc.getCompanyRef() ); workflowColln = company.getExtensionCollection("APPR_ROUTING"); // Group is added as ANYONE CAN APPROVE. ANY = 1 means all // must approve. // ANY = 0; // Go through the metadata and look for a match // More than one match is OK © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

36

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

Postscript

3.9.2.1

Scenario - End of Workflow Processing

The following script is implemented as postscript on the final activity. Its purpose is to advance the document under workflow to the next phase and also to lock an amount field that is considered pivotal to the approval. // If not denied move forward to RFP status // if(getApprovalStatus() != DENIED) { home = IBeanHomeLocator.lookup(session, ProjectIBeanHomeIfc.sHOME_NAME); home.upgradeToEdit(doc); home.changePhase(doc, "RFP"); IapiDocumentLockManager.lockField(session,doc,"FundingRequest"); }

3.9.3

PreCancelScript

3.9.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. © 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

37

doc.getIBeanHomeIfc().upgradeToEdit(doc); home.changePhase(doc,"Request in Draft");

3.9.4

Change Approver

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

Getting the Submitter of a Workflow

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

38

Appendix A: Scripting Guidelines A.1 Design    

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

A.2 Writing Scripts       

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

A.3 Exceptions   

Comment the top of the script with a failure message that describes where the script is executing from. Always use resource IDs for scripted exceptions. Always use the object’s method for creating exception on that object.

A.4 General     

Do not use Internal APIs. Do not access the database directly. Only access objects from the home interface and even then, with utmost consideration to system resources especially on methods like findWhere(). If indirectly accessing an object using getFieldMetadata( ), use the property field on the IBean only. If an attribute has no property field and the object does not have an IAPI, contact support to request that it be added.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

39

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

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

40

Copyrights, Trademarks, and Disclaimers © 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, 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.

© 2013 SAP AG. All rights reserved.

SAP Sourcing 9.0 Scripting and Workflow Guide

41

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.

© 2013 SAP AG. All rights reserved.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF