SAP WORKFLOW BUSINESS PROCESS AUTOMATION 9789388176538

Demystifying “SAP Business Automation” and shape tangible use cases that add values to your organization, Customers &

325 13 18MB

English Pages 0 [327] Year 2019

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

SAP WORKFLOW BUSINESS PROCESS AUTOMATION
 9789388176538

  • 1 1 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

SAP Workflow Business Process Automation by Sudipta Malakar

FIRST EDITION 2019 Copyright © BPB Publications, INDIA ISBN: 978-93-88176-53-8 All Rights Reserved. No part of this publication can be stored in a retrieval system or reproduced in any form or by any means without the prior written permission of the publishers. LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY The Author and Publisher of this book have tried their best to ensure that the programmes, procedures and functions described in the book are correct. However, the author and the publishers make no warranty of any kind, expressed or implied, with regard to these programmes or the documentation contained in the book. The author and publisher shall not be liable in any event of any damages, incidental or consequential, in connection with, or arising out of the furnishing, performance or use of these programmes, procedures and functions. Product name mentioned are used for identification purposes only and may be trademarks of their respective companies. All trademarks referred to in the book are acknowledged as properties of their respective owners. Distributors: BPB PUBLICATIONS 20, Ansari Road, Darya Ganj New Delhi-110002 Ph: 23254990/23254991 MICRO MEDIA Shop No. 5, Mahendra Chambers, 150 DN Rd. Next to Capital Cinema, V.T. (C.S.T.) Station, MUMBAI-400 001 Ph: 22078296/22078297 BPB BOOK CENTRE 376 Old Lajpat Rai Market, Delhi-110006 Ph: 23861747 DECCAN AGENCIES

4-3-329, Bank Street, Hyderabad-500195 Ph: 24756967/24756400 Published by Manish Jain for BPB Publications, 20, Ansari Road, Darya Ganj, New Delhi- 110002 and Printed him at Akash Press, New Delhi. Table of Contents Chapter 1 SAP Business Workflow Introduction 1.1 What is SAP Business Workflow 1.2 Need of SAP Business Workflow 1.3 Why to use SAP Business Workflow 1.4 Benefits of SAP Business Workflow 1.5 When to use Workflow 1.6 How to use Workflow 1.7 Workflow Components 1.8 Business Process & Workflow 1.9 SAP Workflow – Technical Principles 1.10 SAP Workflow – How it Works 1.11 SAP Workflow – Architecture 1.12 SAP Workflow – Best Business Practices 1.13 Steps in Workflow implementation 1.14 Implemented scenario for Workflow 1.15 Troubleshooting with Workflow 1.16 Steps types in Workflow? 1.17 Find a Standard Business Object – Which Relates to the Desired Master Data 1.18 Create a Business Object 1.19 Create an Event 1.20 Create a Method 1.21 Create Key Field 1.22 Implement Business Object 1.23 Create Workflow Task 1.24 Set Up Containers 1.25 Assigning Agent to a Task 1.26 For this Demo Example, you will Trigger the Event by Writing a Custom Code 1.27 A Single Step Task 1.28 How are Workflows Created in a System?

1.29 How Workflow gets Executed 1.30 Workflow Toolbox – SWUS 1.31 Object Types and Workflow 1.32 Interfaces and Workflow 1.33 Key Fields and Workflow 1.34 Attributes & WORKFLOW 1.35 Methods & Workflow 1.36 Events and Workflow 1.37 Types of Event Creation 1.38 Using Customizing for Event Trigger 1.39 Event Creation of Change Document 1.40 Event Creation of Status Management 1.41 Event Creation of Message Control 1.42 Using ABAP Code 1.43 Event creators, receivers, and event linkage 1.44 Type Linkage Entry 1.45 Agent – Workflow 1.46 Types of Agents – Workflow 1.47 Tasks: Possible Agents & Default Roles – Workflow 1.48 How are selected agents determined with and without a default role? 1.49 How are Selected Agents Determined with a WF Agent? 1.50 Rule Basics – Workflow 1.51 Rule definition in an activity step type – Workflow 1.52 Rule definition with Responsibility: Example 1.53 Evaluation path as Rule 1.54 Role resolution 1.55 Role resolution with function modules: Example 1.56 Execution of a Role Resolution via Organizational Objects 1.57 Tasks: Possible Agents & Default Roles 1.58 How are Selected agents Determined with and without a default Role 1.59 How are Selected Agents Determined with a WF Agent 1.60 Organizational Structure Business Scenario 1.61 Organizational Management 1.62 Create Organizational Plan

1.63 Assignment Workflow Task Organizational Objects 1.64 Transaction – PPOCW 1.65 Event Trace- SWEL 1.66 Event Trace – SWELS 1.67 Event Log Details 1.68 Workflow log-SWI2_FREQ 1.69 Workflow log-SWI2_FREQ – Normal View 1.70 Agents involved in Workflow 1.71 Workflow log-SWI2_FREQ – Graphical View 1.72 Workflow log-SWI2_FREQ- Technical View 1.73 Some Important Jobs – WORKFLOW 1.74 Workflow Explorer – SWDM 1.75 Test your Knowledge – Workflow 1.76 Work item Types – Workflow 1.77 Business Object Repository (BOR) 1.78 Some common Business Objects and Interfaces 1.79 Object Type – Release Status & Workflow 1.80 Subtype & Workflow 1.81 Delegation & Workflow 1.82 Objects in the Workflow 1.83 Business Objects – Programming and Workflow 1.84 Writing/Reading container elements defined as field values – Workflow 1.85 Container Macros & Workflow 1.86 Single and Multistep Tasks and Workflow 1.87 Task Definition – Synchronous and Asynchronous Methods and Workflow 1.88 Defining a Task & Workflow 1.89 Setting for Tasks – WORKFLOW 1.90 Work item Text – Workflow 1.91 Workflow definition steps 1.92 Types of Containers – Workflow 1.93 Workflow Container 1.94 Task Container 1.95 Other Types of Container – Workflow 1.96 Binding – Workflow 1.97 Container & Dataflow – WORKFLOW

1.98 What is a Container 1.99 Defining Container Elements 1.100 Some Standard Container elements 1.101 Some Key features 1.102 Container Marcos – Workflow 1.103 Writing/Reading Container Elements Defined as Field Values 1.104 Macros for object definition and declaration 1.105 Workflow and ALE 1.106 Workflow and Error Notification 1.107 Active Monitoring 1.108 Setting up Inbound Process via Workflow 1.109 Notification of Successful Posting 1.110 ALE error handling 1.111 Some important Transaction codes / tables – Workflow 1.112 Workflow Customizing – SWU3 1.113 Workflow log-SWI2_FREQ 1.114 Maintain Start Conditions for Workflow: SWB_COND 1.115 Some Important Diagnosis Transactions – Workflow 1.116 Some Important Tables 1.117 Workflow with Function Modules and Reports 1.118 Standard Rules 1.119 Some Important Jobs 1.120 Some Workflow Concepts 1.121 Automatic Email Sending Functionality in Workflows and Customization 1.122 Debugging a Background task in SAP Business Workflow 1.123 Business Workflow Administration – SAP – Simple Procedure 1.124 SAP Workflow log 1.125 Work Item Monitoring 1.126 Error Monitoring, Analysis and Restarting 1.127 Workflow Error Log Notification Chapter 2 SAP Business Workflow Introduction 2.1 Purpose of the Document 2.2 Benets to Business 2.3 Attributes of developed report

2.4 Technical Details 2.5 Test Results 2.6 Reference Documents Chapter 3 SAP Business Workflow Terminology 3.1 Purpose 3.2 Glossary Chapter 4 SAP SAP Workflow with Function Modules and Reports 4.1 Purpose 4.2 Details Chapter 5 SAP Workflow Review Checklist 5.1 Purpose 5.2 Business object / Class object 5.3 Task 5.4 Workflow Template 5.5 Configuration 5.6 Performance checks Chapter 6 Demo – SAP Workflow for Credit Memos 6.1 Business Requirement 6.2 Credit Memo Workflow 6.3 Organization structure 6.4 Positions 6.5 Users 6.6 Raising a Credit memo 6.7 Editing Organizations / Positions 6.8 Setting the Credit memo level on a Position 6.9 Assigning Users Chapter 7 Demo – SAP Business Workflow – Substitution 7.1 Substitution 7.2 Defining Substitution Profile 7.3 Defining Task Classes 7.4 Assigning Task classes to Substitution Profiles 7.5 Assigning Task classes to Dialog task Chapter 8 Demo – When a FI Document is Parked then Trigger Custom Workflow 8.1 Introduction 8.2 Business Scenario

8.3 Notifications 8.4 Business object used 8.5 Creation of Workflow – Steps 8.4 FI Parking Workflow Configuration Steps 8.6 Summary Chapter 9 Demo – Goods Returns Workflow 9.1 General Information 9.2 Business Needs and Requirements 9.3 Issues 9.4 Selection Screen Details 9.5 Current Functionality 9.6 Desired Functionality 9.7 Technical Details 9.8 Starting Conditions 9.9 Security Requirements/ Authorization Details 9.10 Data Mapping Tables 9.11 Desired Report Design/Layout 9.12 Report Example 9.13 Custom Tables/Structure in Sap 9.14 Recovery and Restart 9.15 Language of Texts 9.16 Currency and Units of Measure 9.17 Assumptions 9.18 Error Handling 9.19 Testing Scenarios Chapter 10 Demo – Workflow for MRP Purchase Requisitions 10.1 Business Requirement 10.2 Solution 10.3 Business Process Flow Chapter 11 Workflow Management System Best Practices 11.1 Introduction 11.2 Purpose 11.3 Best Practices – General 11.4 Best Practices for Design and Development

11.5 Best Practices for Support and Maintenance 11.6 SAP Best Practices & Lesson Learnt Chapter 12: Earn value – Overview 12.1 Introduction 12.2 Overview . 12.3 Project Managers Cost Formulas Chapter 13 Basic OData Services Using SAP NetWeaver Gateway 2.0 13.1 Introduction 13.2 Required Skills 13.3 Optional Skills 13.4 Software Pre-requisites 13.5 Objectives 13.6 SAP User Experience Journey 13.7 SAP NetWeaver Gateway Architecture 13.8 Deployment Option 13.9 REST definition 13.10 What is OData 13.11 Entity Data Model 13.12 Service Development 13.13 Live Demo – SAP Netweaver Gateway 13.14 Use Case 13.15 Solution Chapter 14 SAP NetWeaver Gateway – Transaction Codes Usage and Purpose 14.1 Overview 14.2 Solution Chapter 15 SAP NetWeaver Gateway Basic Configuration Chapter 16 Demo – Workflow Trigger using HR Tables Chapter 17 Demo – Workflow Trigger using Status Management Chapter 18 Demo – Leave Request Workflow 18.1 Overview 18.2 Business Requirements 18.3 Technical Details 18.4 Notes 18.5 Business Solution

Chapter 19 Demo – Integration of Portal and SAP Workflow Chapter 20 Demo – Integration of Workflow with ALE Chapter 21 Demo – Attach Link in send mail Step of a Workflow Chapter 22 Case Study – Advance Workflow Design – Update Sales Document Chapter 23 Case Study – SAP Workflow Upgrade from 4.6 to 6.0 Chapter 24 Quiz Session – SAP Workflow Preface Notice how SAP has changed the world now. Whether you are a newbie or an old-hat, you can learn to design & build simple and advanced SAP Workflow, SAP NetWeaver Gateway by using this comprehensive artifact. You can also enrich your skillsets with the use new object-oriented automation business approach. Use this detailed programming referral guide to develop and optimize your applications. You’ll be programming for SAP in no time. The goal of writing this book is to describe different SAP programming best practices, Tips & Tricks, Real-Time Demos, Case Studies, Quiz, earn value calculation, troubleshooting & performance optimization techniques taken reference from different SAP, professional & IBM blogs, books, articles, Global networks, Wikipedia, organizational forums, portals, etc. The Book is written for SAP Consultants, architects, Managers, Leaders, business executives, Directors & above delegates and for all IT professionals with the objective to provide practical and deep insights on SAP Workflow, SAP NetWeaver Gateway, practical exercises for programming in SAP Business Workflow for all the major SAP applications, Hard coding – categorization & recommendations, step-by-step instructions for adapting data flows, agent determination, event definitions, & more, examples, problem solutions, and tips and tricks for daily practice including SAP Workflow upgrade from 4.6 to 6.0. This book promises to be a very good starting point for beginners and an asset for those having insight towards programming. I am indebted to my Father (Shri Ganesh Chandra Malakar, Retired Professor) as without his support it was not possible to reach this Milestone. It is said “To err is human, to forgive divine”. Although the book is written with sincerity and honesty but in this light, I wish that the shortcomings of the book will be forgiven. At the same the author is open to any kind of constructive criticisms and suggestions for further improvement. All intelligent suggestions are welcome and the author will try their best to incorporate such in valuable suggestions in the subsequent editions of this book. Acknowledgement No task is a single man’s effort. Cooperation and Coordination of various peoples at different levels go into successful implementation of this book. There is always a sense of gratitude, which everyone expresses others for their helpful and needy services they render during difficult phases of life and to achieve the goal already set. At the outset I am thankful to the almighty that is constantly and invisibly guiding everybody and have also helped me to work on the right path. I am son of Retired Professor (Shri Ganesh Chandra Malakar). I am indebted to my Father as without his support it was not possible to reach this Milestone. I am very much thankful to my parents, spouse, son and family for their guidance which motivated me to work for the betterment of consultants by writing the book with sincerity and honesty. Without their support, this book is not possible. I wish my sincere thanks to colleagues who helped and kept me motivated for writing this text. We also thank the Publisher and the whole staff at BPB Publication, especially Mr. Manish Jain for motivation and for bringing this text in a nice presentable form. Finally, I thank everyone who has directly or indirectly contributed to complete this authentic work.

Introduction Notice how SAP has changed the world now. Whether you are a newbie or an old-hat, you can learn to design & build simple and advanced SAP Workflow, SAP NetWeaver Gateway by using this comprehensive artifact. You can also enrich your skillsets with the use new object-oriented automation business approach. Use this detailed programming referral guide to develop and optimize your applications. You’ll be programming for SAP in no time. The goal of writing this book is to describe different SAP programming best practices, Tips & Tricks, Real-Time Demos, Case Studies, Quiz, earn value calculation, troubleshooting & performance optimization techniques taken reference from different SAP, professional & IBM blogs, books, articles, Global networks, Wikipedia, organizational forums, portals, etc. The Book is written for SAP Consultants, architects, Managers, Leaders, business executives, Directors & above delegates and for all IT professionals with the objective to provide practical and deep insights on SAP Workflow, SAP NetWeaver Gateway, practical exercises for programming in SAP Business Workfow for all the major SAP applications, Hard coding – categorization & recommendations, step-by-step instructions for adapting data fows, agent determination, event definitions, & more, examples, problem solutions, and tips and tricks for daily practice including SAP Workfow upgrade from 4.6 to 6.0. This book promises to be a very good starting point for beginners and an asset for those having insight towards programming. The book has been written in such a way that the concepts are explained in detail, giving adequate emphasis on examples. To make clarity of the programming examples, logic is explained properly as well discussed using comments in program itself. The book covers the topics right from the start of the software using snapshots of starting the software and writing programs into it. The real-time examples are discussed in detail from simple to complex taking into consideration the requirement of IT consultants. Various sample projects are included in the Book and are written in simple language to give IT consultants the basic idea of developing projects in SAP new technologies. The examples given in book are userfocused and have been highly updated including topics, figures and examples. The book features more on practical approach with more examples covering topics from simple to complex one addressing many of the core concepts and advance topics also. The book is divided into the below sections. SAP NetWeaver Gateway Earn Value Overview Real-time Case Study and demos on workfow for all the major SAP applications Step-by-step instructions for adapting data fows, agent determination, event definitions, and more SAP Workfow upgrade from 4.6 to 6.0 Examples, problem solutions, and tips and tricks for daily practice Practical exercises for programming in SAP Business Workfow Troubleshooting & performance optimization techniques Hard coding – Categorization & Recommendations Quiz 1 chapter SAP Business Workflow Introduction What do you find in this chapter? 1.1 WHAT IS SAP BUSINESS WORKFLOW Workflow is defined as the automation of a business process, in whole or part, during which documents information or tasks are passed from one participant to another for action, according to a set of procedural rules. This primarily involves coordinating: SAP Business Workflow ® is a cross-application tool that makes it possible to integrate business tasks/processes between applications.

Shis tool was introduced in R/3 Release 3.0A, and received a substantial facelift in the Enjoy Release, 4.6A, which warranted the new name Workflow Builder. Workflow ensures that the right work is sent to the right person at the right time in the right sequence with the right information. Workflow may be defined as technological representation of Business process which in simple words means automation of a business process, in whole or part, during which documents, information or tasks are passed from one participant to another for action, according to a set of procedural rules. In the early days of Workflow, work was passed from one participant (or worker) to another. The main benefits were that work was delivered to people, and each worker could assume that work was ready for processing, because the Workflow system would not forward incomplete items. Delivery was automated. Now Workflow technology has matured; it is the process itself that is automated. A work item or data set is created, and is processed and changed in stages at several processing points to meet business goals. Most Workflow engines can now handle very complex series of processes. Any condition that can be expressed mathematically can be managed by a Workflow system. Workflow has a practical effect on business operations. See how Workflow has changed the business scenarios. Let us take for example of an organization in which a business department receives applications for loans, sorts, and reviews them and then decides whether to grant the loan. The process mentioned, have been simplified to help show the impact that Workflow has. Hereafter, we will refer SAP Business Workflow as simply Workflow throughout the document. The Manual Process - Before Workflow For an example, consider the process of getting a loan from a bank. Right from accepting the application to delivering the loan, there are numerous people and documents are involved. When this process is handled manually, most of the times it is likely to be inefficient because following reasons: The Automated Process – Workflow Era All the above said problems with the manual processes can be eliminated using Workflow. With Workflow system in place, the business processes get accelerated at enormous rates and so does the customer satisfaction level. Few direct advantages are as follows: With Workflow handling the routine work, the supervisor is only required to handle exceptions. The logic in Workflow engines is quite capable of deciding whether a loan should be granted or not. With Workflow, the basis of the decision can now be determined automatically, 24 hours a day. This is becoming a requirement of participating in web-based e-commerce. Customers expect to be able to contact you and do business at any time of day. E-commerce also means that for many businesses, sales opportunities can arrive from any time zone on the planet. However, for automating a process we should be able to justify the use of Workflow for the same. Preliminary, following parameters can be considered to decide whether a process is suitable for Workflow: 1.2 NEED OF SAP BUSINESS WORKFLOW

Drawbacks Inefficiency Each lacks a way to trace where a task is Who executed or is executing it How much time it required 1.3 WHY TO USE SAP BUSINESS WORKFLOW Workflow ensures that the right work is sent to the right person at the right time in the right sequence with the right information Tool for business processes automation Not tied up to any particular application Operates uniformly across applications Coordinate all participating tasks Provide users with active support Intelligent routing Guarantees a standard approval process (Always ensures that the correct business procedure is followed) Guarantees tracking of approval process historically (Workflow logs) Guarantees cycle time of approval process (if escalation procedures have been built in) Guarantees fault tolerance, i.e. : Workflow can be restarted from error point Guarantees compliance with the pre-defined process To Reduce Business Process Lag Time Most business processes follow the 90/10 Rule. At least 90% of the total time consumed by typical business processes is for ‘lag time.’ These are the time tasks that are waiting in the in-baskets or queues of the performers, in transit, or consumed in tracking status. It is dead time that does not add any value to the business.

Experiments have proved that, only 10% of the total process time is consumed by the task time , the time performers spend working on the tasks. Workflow automation attacks the lag time or dead time. If the lag time is reduced by 50%, the overall process time is reduced by 45%. To Provide a Single View for Tasks Workflow automation decreases task time by putting all tasks for someone in one central easy-to-find location. SAP can perform all calculations and rules-based decisions automatically within the electronic forms. Tasks Don’t get Lost, Processes Finish to Completion The administration view allows you to track and organize all the tasks of every participant in Workflow processes. Additionally, if tasks are late, reminders are sent. Comprehensive Workflow automation ensures that tasks do not fall through the cracks. Have the Right People Deal with the Task This is a key benefit and efficiency gain. The Workflow software will route tasks to the right individuals for approval and input based on your business rules. This means that exceptions are dealt with properly and more importantly tasks don’t get ignored because the person, who has got them, doesn’t know what to do. A further benefit is that when you define the business rules and Workflow routing, you ensure the correct people make business decisions. 1.4 BENEFITS OF SAP BUSINESS WORKFLOW

Reference – SAP AG 1999

Reference – SAP AG 1999

Reference – SAP AG 1999 1.5 WHEN TO USE WORKFLOW It is particularly beneficial: when different people are involved in different parts of the process when the users need to be reminded of what they need to do when the duration of the process is critical and deadlines have to be met when process-tracking or auditing is critical when the process-consistency is critical when the process is repetitive in nature and Rule based By automating the process, you free the users from having to know what to do when. Work items are sent to the participants notifying them of what they have to do, and a single click on the notification calls the correct transaction and navigates to the relevant screen. 1.6 HOW TO USE WORKFLOW (Common examples) 1.7 WORKFLOW COMPONENTS SAP Business Workflow Components are generally divided into three Categories:

1.8 BUSINESS PROCESS & WORKFLOW Event In my organization, Whenever a material is changed , the Person responsible is informed of the change who either approves or rejects the change . Agent

Task

Reference: SAP AG 1999 Explanation: Objects and Object Type The data in Workflow is described by Object type, e.g. MATERIAL . Methods (is in part Object Types) – Here, activities are defined and get executed with data. Creation of material can be considered as an example. Tasks Tasks describe elementary business activities. The method of the object has been always referred by these. Background tasks or dialog tasks can be considered as tasks types. Workflow Builder Workflow definitions are defined which are made up of steps, the Workflow are controlled by steps. This linking is defined in Workflow Builder. Workflow definition controls the order of piece of work and any temporary data needed along the way. Workflow definition consists of the following: Control logic or

Actual piece of work to be executed i.e. Task Organizational Plan It allows the Workflow System to determine the Agents of individual Tasks at runtime. Event Events are occurrence of status changes of an object. Workitem Work Item represents a Task or Action in the Workflow System at Runtime. Work item is just like emails generated at run-time notifying the agent that he need to do something. Workflow Manager: It is for Workflow Control and Workflow Coordination. Work Item Manager: It manages execution of individual Work Steps, known as Work Items) including assignment to agents and deadline monitoring. 1.9 SAP WORKFLOW - TECHNICAL PRINCIPLES The execution & definition of Workflow can be divided into four Main Areas Business Workplace Workflow Builder Tasks Business Object Repository (BOR) Business Workplace / SAP Office (Transaction Code SO01) A user’s integrated work area for the following: Processing work items Receiving and sending messages Managing documents and work processes Distributing and processing information for the whole enterprise or particular groups BOR (Business Object Repository) It is the central repository within the R/3 system containing all the business object types and SAP Interfacetypes together with their definitions and methods.

Reference: SAP AG 1.10 SAP WORKFLOW – HOW IT WORKS

A Workflow can be started in two ways: Manually ( Office → Start Workflow ) Automatically using events Event : Occurrence of a status change of an object Events – Examples: Order canceled Project milestone reached Budget limit reached Events Used: Triggering Events: To Start Workflow tasks. Terminating Events: To End the Workflow. Application Creates Event through:

Change Documents: Status changes of objects which are logged as change documents can be reported as events. Status Management: An event can be created automatically for objects using the general status management when an object status changes. Message Control (NAST table): Programming (Explicit event creation) using Function Modules: Events can be created by calling the relevant function module SWEEvENTCREATE . Event Container The event container contains the event parameters as container elements. If you define triggering events or terminating events for a task, you can specify the binding from the event container to the task container. The event container contains Workflow system elements as standard. You can add more container elements to the event container within object type definition in the Business Object Builder . Using Linkages A linkage defines the assignment of events to the event receivers interested in them. The potential receiver of an event must define the linkage. This can be done using function modules provided or a maintenance transaction. The Workflow system in the form of the event manager evaluates all the events created. In doing this, the event manager carries out the following steps:

Reference: SAP AG 1.11 SAP WORKFLOW - ARCHITECTURE

1.12 SAP WORKFLOW - BEST BUSINESS PRACTICES Speed Time to Market Accelerate the execution of SAP Transactions by routing information quickly to users for immediate action; Ability to substitute; Ability to Forward Work Items Improve Quality and Decision Making Deliver accurate information to Process Participants; both within the Enterprise and Externally; Ability to attach documents and Objects to a work item Improve Operational Efficiency Prevent duplication of effort; Pre-defined Business Process and Actors. Eliminate time wasted waiting to take action . Ensure Compliance Monitor and Control Processes; Deadline Monitoring and Escalation Procedures 1.13 STEPS IN WORKFLOW IMPLEMENTATION Put in simple words, Workflow is used for communicating from one program to another one. The precedent program triggers an appropriate event which in turn incarnates an instance of the Workflow template and all the inclusive steps are executed in a pre-planned and controlled manner. Steps followed for Workflow Implementation Different elements used in Workflow are as follows: Object: Elements of business objects are: Attributes, methods, and events. A business object can be edited for the same using SWO1 transaction. Event: An event describes a possible change in status of an object in R/3. Before an event can be used in a Workflow, in the business object repository it must be defined for the object type. Triggering an event can be implicit or explicit. Event can be triggered implicitly in the following ways: Event can be triggered explicitly using function module: Different agent assignments possible are as follows: User, Workflow Initiator, Organization unit, position, job, role. Step: Individual steps in a modular fashion, makes a Workflow definition. The step type must be specified first when creating a step in a Workflow

Step: Individual steps in a modular fashion, makes a Workflow definition. The step type must be specified first when creating a step in a Workflow definition. The following step types exist: Steps that relate to business activities: Activity, user decision, document from template, Web activity. Steps – fork, container operation, event creator, wait step, internal process control & monitoring, Condition, multiple condition, loop. Task: Tasks describe a business process. A task refers to a method of an object type and represents one step in the business process. Role: Role resolution enables you to restrict the number of possible agents for a work item. Role resolution determines which responsible agents have a property described by a rule. This improves the ability of SAP Business Workflow to get the relevant task to the relevant person at the right time. There are various ways of defining the rules. You can use the following: Function modules : You use a function module to define standard roles if the agent for a task must be found according to extremely complex selection criteria. If you define roles using function modules, the system find agents by executing the function. How data is obtained, varies from function to function. You can use predefined functions, or create your own functions. Organizational data : You use organizational data to define standard rules if your business processes are managed based on your organization model. If you define rules using organizational data, rule resolution traces the possible agents for a task by using the relationships between the task, the objects in organizational management, and the SAP organizational objects. Responsibilities : You use responsibilities to define standard rules if you need more precise selection criteria to find agents, but do not want to use function modules. You can also use the organization model to find possible agents using jobs, positions, etc. Work item : Task at runtime is known as Work item. Workflow Development Approach We are proceeding with the receiving-end to triggering-end approach. The impetus to run the entire process is provided by an event which gets sparked off by the triggering process. The triggering event is included in the business object. A business object is an entity that encapsulates business data and functions. It also comprises the events that are associated with the methods. As the process is programmed, various methods of the business objects are called to perform the desired tasks. Explains the chronological sequence of elements involved in Workflow. General steps which can be followed for Workflow development are as follows:

Flow of Data through the Workflow This function module returns ID of the event created, which can be used for event tracing. 1.14 IMPLEMENTED SCENARIO FOR WORKFLOW The typical scenario where Workflow can be implemented is triggering an outbound IDOC processing from inbound IDOC processing. A document like a query, notification or request must be operated on and after processing the data and going through all the business validations, we can send a response against the inbound document. The response means posting the data, sending confrmation or rejection over a business document.

There are different ways of integrating the two processes like SUBMIT Program from the inbound process or batch scheduling of the background job for outbound process. However, these methods along with simplicity bring in their own demerits. In case of SUBMIT Program, termination of outbound program (e.g. exceptions or ABAP dump) will propagate its impact on the inbound process as well, even if the inbound process has been successfully executed. In this case there is no option but to restart right from the inbound processing. For batch scheduling, firstly user must execute the job through SM35, and secondly if the task fails, user must execute the task manually flling all the data. The situation requires a communication channel that couples the two applications to ensure flow of data, at the same time retaining their individuality to safeguard the inbound process against the baneful impact, if any of the outbound process. Workflow serves as a feasible solution here, thanks to its modularity and fexibility. Another motive behind using Workflow is the ability to reprocess the failed records after fxing the problems. To serve this purpose, we have created two steps in parallel; one will be running foreground and the other in background. If the background task is successful, foreground task will be logically deleted, in case it fails, user can always run the foreground work item after the cause of error has been rooted out. The Workflow template is illustrated in the following figure:

1.15 TROUBLESHOOTING WITH WORKFLOW Following are the tips to solve the most common problems that one may encounter while testing a Workflow template. 1.16 STEPS TYPES IN WORKFLOW? The Workflow template ofers following features in its numerous tasks. A brief account about these steps is given below. All these features are available in different tab-pages of the corresponding steps.

Activity This is a simple step which executes the underlying standard Task. For execution of this activity, you need to fill the container of task. The agent assignment is carried forward from the standard task. It ofers a facility to notify a user on successful execution. You can choose to track the completion of this activity. There are three ways you can set the latest completion time based on: from start of Workflow, start of work item or from a user specified date and time. The issue of missed deadline can as well be escalated to the earmarked user. In a similar way you can control the starting time of the activity and latest starting time of the activity. Here also you have provisions also to notify the concerned person about the missed deadline. Methods : you can allow some methods to run simultaneously with, before or after execution of the activity. You have an option to individually process each record of multiline elements specified. For each record a work item is created at runtime, with the maximum limit of 99 records. The corresponding steps are processed in parallel. Priority can be set to the activity from 1 (highest) to 9 (lowest).

Web Activity This step uses an existing Workflow step as a reference and sends the container elements to an XML document. The XML document contains the operation CreateProcessInstance , which starts a remote process.

Document from Template This step enables us to create a document runtime using the data in the containers. You can create an Excel sheet, Word Document or even a PPT presentation and slides to display the data. For this, you must create the templates first, carrying references to the container variables. Then at runtime, the template and flow items are passed from Workflow container to the task container for processing. The features like monitoring start time, end time, setting priority, notification etc. are also available here.

Condition Condition gives us a better control over the process flow. Here based on the value of certain elements, you can decide the steps to be executed. You can create a condition using any of the container elements and imposing on them all mathematical comparison operators. The condition gives two outcomes (Condition True and False) where you can design our process flow.

Multiple Condition The multiple condition serves like Case-When statement. Based on all possible values of a container element, you can decide the route to be taken.

Event Creator You can artificially generate events of the objects that are a part of Workflow container. This is particularly useful when you intend to trigger a Workflow from the other.

Wait for Event After a certain step in the process, a situation may arise where you must wait for an action to be taken by the user within a stipulated time. In such cases you can use this step called Wait for event. You can set the timeline for awaiting the event with reference to Workflow creation, Work Item creation or user specified date and time. All usual features like monitoring start time, end time, setting priority, notification etc., are available.

Container Operation Here you can manually assign values to the required container elements. This is useful especially while setting/ resetting the counters for running loops.

Process Control This allows us to execute certain decisive actions on the Workflow in certain exceptional cases. Following operations are possible. Cancel the specified Work Item. The work item is set to status logically deleted. The prerequisite is that the process control should be in a branch parallel with the work item. Cancel Workflow. All the Workflow steps are set as logically deleted. If this Workflow is being called by another one, the calling Workflow is set to status Incorrect. Terminate Workflow. Workflow status is changed to Completed. Set the given work item (again this should be in parallel with the process control) to obsolete.

User decision This step is useful for seeking approval for a certain task. You can send a proposal to a user informing him about a case (Te Workflow container elements can be used for conveying actual figures.) and put some options like ‘accept or reject before him. Based on his decision, you can steer the flow of process. Besides user, this decision can be sought from a Role, Position, Job or Organizational Unit. Usual monitoring features can be used.

Until Loop For repetitive processing of steps, you have two flow control loops at our disposal viz. Until Loop and While Loop. The until loop asks for a mathematical or logical condition and keeps on running the loop until the condition is true. The condition is checked after every iteration. If it is true, the loop is terminated; if it is still false, new iteration is started. It is strongly recommended that in every case a provision be made to terminate the loop at some instance.

While Loop Here you can have different steps executed depending upon the actual value held by a container element referred to as Comparison Basis. After every pass, the variable will be checked and the corresponding route will be processed. If the variable encounters any value other than specified, the loop is terminated.

Fork Fork is useful for parallel processing of activities which are not inter-dependent. You can bring out as many branches from a single point as you need and all of them will run simultaneously. Later on, all of them fuse into one point. have the privilege to specify the minimum number of branches that must be completed before moving on to further steps.

Send Mail A mail can be sent to the SAP inbox or even outlook mailbox, of course this needs some configuration with the mail server. You can send mail to any user, Organizational Unit, Role, Job or Position. You can also choose to mail Workflow initiator i.e. the user who has triggered the Workflow. The container data can be used in the mail. The option of sending express mail is also available.

Undefined This is a blank step created. You can create the desired step on this place later. 1.17 FIND A STANDARD BUSINESS OBJECT - WHICH RELATES TO THE DESIRED MASTER DATA Reference: Arnab Dhar, Sangram Chowdhury’s Artefact Transaction SWLD Definition Tools —> SAP Business Workflow —> Development —> Definition Tools —> Business Object Builder (Transaction Code SW01) Click on Business Object Builder. The initial screen appears as follows. Either search for an object by name in short description. Or use the IMG structure, which is accessed via the Business Object Repository button.

Position mouse cursor in the feld Object/interface type and hit F4 → In the pop up window click Information System → Search the business object created earlier or SAP standard business object. → Select it and click on Display .

Select all object types and the following screen appears. Here the businisess object BUS2054 has been explored, which is under Project Systems .

A business object has the following components as shown in the following figure:

A screen showing the components of the object is dispalyed as the following figure: 1.18 CREATE A BUSINESS OBJECT Give the business object name prefxed with Z_. Enter the following felds with the values: Object type: Z_TESTXX This is the internal technical key. Object type can have maximum 10 characters. This must be unique across all the object type. Objects are specifc instances of object types at runtime. Object name: ObjectNamefor_XX The object type is addressed with this name by external applications. This is a descriptive English name and can be up to 32 characters. This also must be unique across all object type. Name: Object Name: XX This is a meaningful name of the business object. Description: Object Description: XX Object description, can be up to 40 characters. Program: Z_TESTXX Each object type has an ABAP/4 program in which methods of the object are implemented. This program is generated automatically when you create or revise an object type. Application: * Page: 53 indicates cross application. Should you need to extend the components of an SAP delivered object, you can create a subtype and then delegate it back up to its super type. This means that the super type transparently acquires the new functionality. If this super type is referenced by any SAP or custom application, the new functionality is available. Any super type may have at most one delegation assigned to it. Delegations are client independent. Use the menu path Settings >System-wide to create a delegation . 1.19 CREATE AN EVENT Open the object type in change mode. When you change your subtype the first step is to create a new event, this is done by selecting the Event node and clicking the create button. Give the event a name and a description. Next set the status of this object type component to be implemented. Event:

ZEVENTXX

Name: Description:

Event name: XX Event Description: XX

Click on the new event and… Edit → Change Release Status → Object Type Component → Implemented (A small box sign vanishes from the right side of the event, indicating that it is implemented) There can be multiple triggering events for a standard/customer task. In R/3 4.0 the release strategy for new Object Types and Object Type Components (methods, attributes, events, etc.) was enhanced. Now when an object type and/or component are created, there are different statuses to select, based on its required purpose. The statuses are as follows: Modeled : Objects cannot be accessed at runtime. This is the status that is automatically set when an object type or component is created. Items with a modelled status cannot be referenced in any type of Workflow task. Implemented : Objects can be used internally in a test environment. Tey are accessible, but may not be stable (especially if no delegation has been defined). Released : Objects are ready for Production. Note : Local objects cannot be released. Obsolete : Objects are typically replaced by new functionality or incompatible with previous versions. This status is optional. 1.20 CREATE A METHOD Next a method must be created without using any function module template. When creating the method, ensure that the method call is synchronous – this means that the method doesn’t require a terminating event. A method can be synchronous or asynchronous. Synchronous Method that, for the duration of its execution, assumes the process control and, after its execution, reports to the calling component (work item manager, in this case). Synchronous methods can return the following data, if defined: Return parameters, one result and Exceptions. Terminating events can also be defined for a single-step task described with a synchronous method. At runtime, the relevant work item is then terminated either when the synchronous method is successfully executed or when one of the defined terminating events occurs. Asynchronous Method Method that, after its execution, does not report directly to the calling component (work item manager, in this case). Asynchronous object methods do not return results, parameters, or exceptions. At least one terminating event must be defined for a single-step task described with an asynchronous object method. At runtime, the relevant work item is only terminated if one of the defined terminating events occurs. Next, set the status of this object type component to implemented. The methods are not implemented unless you once open their program. Select the method and open its program. It gives a message Do you want to generate a template automatically for the missing section . Click Ye s . Inside the program, insert the code “CALL TRANSACTION ‘FB03’. Display Financial Document. Edit → Change Release Status → Object Type Component → Implemented 1.21 CREATE KEY FIELD Create key felds with ABAP dictionary feld proposal. It is the identifying key, via which the system can access a specifc object, that is, an instance of the object type. The key felds of an object type are usually also the key felds in the table containing the header data for the object type. Only character-based data types are allowed as key felds. The total length allowed for all key felds is 70 characters. Each key feld refers to a feld in the ABAP Dictionary. Enter BKPF in table name feld and select all the key felds. Press the Continue button. Next, set the status of these key felds to be implemented.

Edit — > Change Release Status — > Object Type Component — > Implemented 1.22 IMPLEMENT BUSINESS OBJECT The whole business object needs to be implemented so click on the business object title and Edit → Change Release Status → Object Type → Implemented Now you can check the syntax, generate the Business Object and then test it. Execute the custom method you created and give the company code, Document number and Year. 1.23 CREATE WORKFLOW TASK Now we need to create a Workflow task, this will be triggered by the event and will call the desired method in your business object subtype/Object type. Tasks to user means generic actions, which are in the responsibility of a person (agent) or group of people (agents), that may have to be done in a predefined interval. Runtime execution of a single step task produces a work item in the selected agent’s integrated inbox. Transaction SWLD Definition Tools → Tasks/Task Group → Create This task will be of type TS (Standard Task) Tasks are of two types. Standard and Customer tasks Standard tasks (object Type TS) are supplied by SAP and can also be created by the customer, they are client independent. Customer tasks (object Type TS) are client dependent and created by the customer. (SAP’s recommendation is that all new tasks should be of type TS) after this is entered click the create icon (Don’t give the Task number, it will be created automatically). This will bring up the main task window. Under the Basic Data tab enter the Abbreviated Name (this name should be unique for tasks), Name and Work Item Text. Enter your business object subtype/ object type name as the Object Type and enter the Method you created within the subtype / object type. If you tick Background Processing as the execution mode, the work item is executed without need for manual intervention. Next, move to the Triggering Events Tab. A new entry can be inserted here in the table – it can reference the business object subtype/ object type and the relevant event. When this event occurs, the system starts this task. Another event is Terminating Event: When this event occurs, the system terminates the work item for this single-step task. (If the single-step task has the property Confrm end of processing, the work item is not terminated when the event occurs. The work item must still be set to Done by one of its recipients.) Use Single-step tasks that refer to an asynchronous method must have at least one terminating event. Single-step tasks that refer to a synchronous method, can have terminating events.

1.24 SET UP CONTAINERS In order to transport relevant data between events, tasks, and methods there are many data containers, which are used in this process, but we need to make a few small modifications to these.

Click on the Containers button. Now click the Create button. Tree felds in the container with reference to the database table can be created. For the first feld give reference table name as BKPF and reference feld name as BUKRS , for the second give reference feld BELNR and GJAHR for the third. Highlight the newly created record in the table under Triggering Event tab and Binding Definition button can be clicked now. How data is transferred from the Event container into the Task container can be shown here as there should be four records. Event Parameter Container button can be clicked now, what data is present in the event for transfer to the task can be shown here. Copy the element name from the screen and insert it in to the associated slot in the binding definition (Enclosed in &’s) in case if there is matching data in the Event Parameter Container. To activate the event linkage is the last step of all, user need to press the small red button to the left-hand side of the event record. When it is activated it becomes green . The link between the event and the task can be created now – and user can call the method, it in turn calls the required transaction or reports or function module. 1.25 ASSIGNING AGENT TO A TASK Determine the possible agents for executing the single step task. An agent is an executor of a work item. Responsibility can be assigned to a single person, to multiple people (a shared task) based on jobs, positions or organizational unit. This fexible assignment provides the greatest stability and maintainability since the tasks do not have to be reassigned every time specifc employee changes and the Workflow definition do not need to be changed. The possible agents designated at the single-step task level must already have SAP authorization to execute the functionality in the method. If they don’t, when the task becomes a work item at runtime and the user attempts to execute it, they will get a message: You are not authorized to execute this transaction .

Agents are an important part of tasks. Agents (capable executors of the task) must be assigned to the single-step task . (Within the task definition, Additional data ® Agent assignment ® Maintain .) These are the agents drawn from the organizational plan who are qualifed to perform the task. 1.26 FOR T HIS DEMO EXAMPLE, YOU WILL TRIGGER THE EVENT BY WRITING A CUSTOM CODE The object/event trigger is the starting point of a Workflow. The possibility of building a Workflow is ruled out without this. The triggering of events is achieved through many mechanisms some of them are listed below: Events can be created in the following ways: Change document Status management Message control Custom code: The function module SWEEvENTCREATE is used to trigger the event. Don’t forget to write a commit work after the function module call. 1.27 A SINGLE STEP TASK By now you have defined a Business Object with key felds Company code, Accounting document number and Fiscal year. You have created a method and an event for the Business Object. You have also defined the Task for linking the method and event and defined containers and performed the binding definition. You have also defined the custom code to trigger the event. Now, your objective is to display financial document using CALL TRANSACTION ‘FB03’, when the event is triggered. For this you must put the following piece of code inside the method of the object and generate it. Check that you have given your username in the agent assignment section of the task. Now when you execute the custom code the event will be triggered, so the key felds will be inside the event container, from there it will pass on to the task containers which you have defined. This transfer is controlled by the binding definition you established before activating the task. From the task container the key felds will be available inside the Business Object. Tus, they will be accessible inside the Object method, where you use them to display the financial document. 1.28 HOW ARE WORKFLOWS CREATED IN A SYSTEM? Within Workflow templates, there is a key with the following structure: From the structure of the 8-digit number, the system knows whether the template is a standard template delivered by SAP or the one created by the customer. Customer-defined templates start with the prefx number that was defined in Customizing for the system and client. 1.29 HOW WORKFLOW GETS EXECUTED

1.30 WORKFLOW TOOLBOX - SWUS In the productive system, workflows are usually triggered by events. You can start a workflow for testing. Transaction SWUI displays a list of small sample workflows. (toolbox principle) You can start the workflows and test them live .

Call the Workflow Builder and view the technical details for the Workflow. Unlike transaction SWUS, which makes system Workflows available to each user it can call, transaction SWUI only shows the user Workflows in which he or she is explicitly named as the agent, or those Workflows created as a general task. In the basic data of a Workflow, you can use the Agent assignment for task icon to maintain the possible agents of a Workflow. 1.31 OBJECT TYPES AND WORKFLOW SAP Business Workflow has been developed on an object-oriented basis. The business object types are identifed and described with their object methods in the Business Object Repository ( BOR ) of the R/3 System. Generally, one object is created in the system and then processed in a Workflow over several steps by various employees. Workflow deals with object types. Object types are definitions of data. In order to access database data, Workflow uses the object type interface. Most of the information represented by object types is available in the ABAP/4 Dictionary.

Objects are created at runtime and are specifc instances of defined object types. Many object types are delivered by SAP. In addition, the customer can create new object types or extend SAP objects by creating subtypes (child objects). New customer objects or subtypes may be desired if the delivered SAP object does not contain all the characteristics (attributes) or processing options (methods) desired. Possible status changes to an object type are defined in events. For example, the material changed event should occur if a material master is changed using transaction MM02.

Creating an event for the object type in the BOR does not mean that it is automatically triggered at the appropriate time. The application must publish the event specifically in the system. Attributes can refer to felds in the DDIC and therefore to a database table, as well as to other object types. For example, the Purchase order attribute in the Material object type refers to the Purchase order object type (BUS2012). At runtime, all purchase orders are available for the P-100 material, for example, and their attributes can be evaluated. You can also access the methods of the Purchase order object type. Methods can refer to all functions defined in the SAP System. A method can call a report, transaction, function module, or any defined or customized ABAP code. 1.32 INTERFACES AND WORKFLOW Interfaces are a combination of attributes, methods, and events to be used in common, among multiple object types. The purpose of interfaces is to define common functionality in one object type, and to assign that common functionality via an interface to multiple object types across the Business Object Repository. This avoids redundancy of data and functionality definition. Each new object type automatically receives the interface IFSAP , the SAP standard interface. IFSAP provides every object type with the following: Method Display Method ExistenceCheck sAttribute ObjectType 1.33 KEY FIELDS AND WORKFLOW Key felds are designed to uniquely identify the object type. If the key feld has a data type reference of a dictionary table feld, the runtime system will look to that table feld to retrieve the value of the key when processing the object. When the key feld is created, the ABAP/4 program code is

generated automatically when the object type is generated. 1.34 ATTRIBUTES & WORKFLOW

Attributes are available as interface elements and can be incorporated into Workflow texts. Attributes are also used in the Workflow definition, for example, when formulating conditions, that is, they are used within the process control. Source : Data type reference : If an attribute refers to another object type, its attributes and methods are also available in the program at runtime. For virtual attributes, customer-specifc source code must be implemented in the program of the object type. Attribute properties : An attribute can have multiple lines (all purchase orders), and/or can be mandatory (must always have a value), or instanceindependent (value does not depend on a particular object, for example, all IDOC message types in the SAP System). 1.35 METHODS & WORKFLOW

Methods incorporate the permitted functions available for an object. For methods to work correctly, you may have to enter import parameters at runtime (defined in the interface for the method). Synchronous methods can return values to the calling program in the form of: Asynchronous methods are the opposite of synchronous methods. Asynchronous methods can have import parameters, but they cannot have export parameters or result parameters. Reason: Asynchronous methods do not send a response to the calling program. To implement the method in the object type, proceed as follows: As far as possible, the system will implement the method in the program when requested.

Methods – Call attributes Dialog/or background: Execution of the method is via a work item in a user’s integrated inbox or in background by the Workflow runtime system. Background methods cannot use messages or exceptions because they cannot be processed by the background system and will result in termination of the program. Synchronous/Asynchronous Synchronous methods finish executing before handing control back to the calling program. These types of methods can return export parameters, results and exceptions. Asynchronous methods do not return control to the calling program immediately. Once executed, they depend upon events to communicate the results of the method back to the calling program. Asynchronous object methods cannot have results, export parameters or exceptions. Result: Synchronous methods may return an export parameter as a result. A result can be defined like a dictionary feld or an object type. Instance independence: Indicates whether an object reference is passed to the method by binding at the time of execution. Methods that generate and return an object reference, such as Create , or methods that generate a report listing should be instance independent. Import /Export Parameters The method parameter container contains references to all import, export, and result parameters which need to be exchanged back and forth between the calling program (single-step task) and the method. Binding is necessary between the single-step task and the method parameter container to accomplish the data transfer. Import parameters are those values which are necessary to execute the method. Import parameters are retrieved from the container CONTAINER using the macro instructions SWCGETELEMENT (single-line) or SWCGETTABLE (multiline). Export parameter values are passed to the container CONTAINER using the macro instructions SWCSETELEMENT (single-line) or SWCSETTABLE (multiline). The result parameter is passed to the CONTAINER element RESULT via the same macro instructions. Exceptions

Error handling is accomplished through the use of method exceptions (synchronous methods only). The Workflow definition can branch according to these possible error states and allow for subsequent steps to handle these conditions. Messages and exceptions cannot be used with background methods because they will terminate the program. Number of the exception: Error type: Message : needs application area and message number. Exceptions are implemented within a method, between the macro instructions BEGIN_METHOD and ENDMETHOD . ExIT_RETURN Code Variable1 Variable2 Variable3 Variable4. The following exceptions (for temporary errors) are also available to allow exiting of the program: 1.36 EVENTS AND WORKFLOW Event parameters are defined to transport runtime application data from the creator of the event (the application) to the receiver of the event (a Workflow, a single-step task, or an asynchronous method needing termination). If the application needs to send any data to the event receivers, event parameter container elements must be created in the definition environment and flled at runtime. Event parameters are defined as elements in the event container. The object type of the event is automatically created as an object reference (event parameter) in the event container.

To create an event, position the cursor on the blue Event branch of the object hierarchy and follow the menu path Edit > Create . Provide an event name, short text, and description. Events are created only symbolically at the object level. Tey must be published by the application code by one of the means discussed in the Event Definition and Implementation chapter. Event names may be defined in lower or upper case, but must be entered in event linkage in all upper case letters. 1.37 TYPES OF EVENT CREATION

There are four ways to create customer specifc instances of events: It is possible to extend an object type with additional events and create these events without additional programming. Only if the configurable event creator does not meet your requirements would you explore creating an event via ABAP/4 application program code. Program code can be used to create the event by: SAP core modification to add the function module to the application code (not recommended). 1.38 USING CUSTOMIZING FOR EVENT TRIGGER

1.39 EVENT CREATION OF CHANGE DOCUMENT

1.40 EVENT CREATION OF STATUS MANAGEMENT

Assign the status object to a schema and specify what event and what object type you want to trigger. Then select the entry and under Status restrictions specify the status that should trigger the event. You can find the system status using transactions BS22, BS12, and BS02. Selecting the appropriate status requires knowledge of the application.

1.41 EVENT CREATION OF MESSAGE CONTROL

1.42 USING ABAP CODE

Programming knowledge is required when calling the function module SWEEvENTCREATE to create an event. You can code this call within a user exit or a custom program (with or without batch scheduling). You must pass the following import parameters: You must pass the following tables parameter: Tips for finding User Exits: Checklist for ensuring the user exit is positioned correctly for Workflow use: ====== INCLUDE . B Tells the program we are using Workflow Macros PARAMETER: SALESORD LIKE VBAK-VBELN. DATA: OBJTYPE LIKE SWETYPECOU-OBJTYPE, Event linkage or transaction SWE2 Each type linkage entry contains the following details: When the event linkage is activated from the triggering event maintenance screen, the enabled indicator is set. This indicator can also be set or not set from the type linkage table entry. Type linkage entries are transportable, but the enabled indicator will always NOT be set in the target system. Type linkage is always client dependent. 1.45 AGENT - WORKFLOW Agent is an executor of a work item. Agent is responsible for executing a task in a Workflow. Agent is determined by the system either through organizational chart or directly if user is assigned as agent for a particular task. If the agents of the individual Workflow steps are determined using the customer-specifc organizational chart, your agent assignment in the Workflow remains fexible to change. 1.46 TYPES OF AGENTS - WORKFLOW

The processing agent: The person(s) who actually processes the work item. The deadline agent: The person(s) informed when a work item is not processed fully within the specified deadline. This notification is received via a deadline work item in the deadline agent’s integrated inbox. The notification agent : The person(s) notifed when an activity step is fully processed. This notification is received via a notification e-mail in the notification agent’s SAP Office e-mail. 1.47 TASKS: POSSIBLE AGENTS & DEFAULT ROLES - WORKFLOW

As we said before, work items are the runtime representation of steps in a Workflow. Steps reference tasks. Tasks are activities which create, delete, change or otherwise afect one or more business objects. Tasks can be single-step or multi-step. Agents are an important part of tasks. Possible agents (capable executors of the task) must be assigned to the single-step task . (Within the task definition, Additional data —>Agent assignment — > Maintain .) These are the agents drawn from the organizational plan who are qualifed to perform the task. Selected agents are derived from all possible agents assigned at the single-step task level. The selected agents can be the same as the possible agents, or a subset of the possible agents derived from a default role . Restriction of the possible agents to a subset is optional. Processing agents, deadline agents, and notification agents can all be specified as subsets of the possible agents using the default role of the task definition. 1.48 H OW ARE SELECTED AGENTS DETERMINED WITH AND WITHOUT A DEFAULT ROLE?

As we said on the previous page, one-way selected agents can be determined is, at the task level is via a default role . A default role can be established in the definition of the single-step task to determine selected agents (from the pool of possible agents) at runtime. (Within the task definition, click on the Default roles push-button). If no default role is indicated at this level, all possible agents are selected to process this task at runtime . A default role is helpful if a single-step task is started by a triggering event. In this event, selected agents can be drawn from the possible agents. If default roles are specified, it may require a binding definition from the task container to the role parameter container. (See the chapter on

Containers, Dataflow and Binding ). Another way selected agents can be determined at the task level is by designating the task a “ general task ” – meaning all users in the system are selected agents unless a default role is assigned. 1.49 HOW ARE SELECTED AGENTS DETERMINED WITH A WF AGENT?

Another way selected agents can be established is via agent assignments . Responsibility assignments can be assigned for a Workflow step. Responsibility is specified at the Workflow step level within the Workflow definition. Responsibilities defined here override the default role established at the task level. When responsibility assignments are in place, changes can be made to the organizational plan, and these changes will automatically take effect on the agents selected in a Workflow definition without changing the Workflow definition. Responsibility assignments for activity steps and user decision steps can be determined by selecting one of the responsibilities below. Processing agents, deadline agents, and notification agents can all be specified with the following designations (only deadline and notification agents can be specified for a wait step. See Workflow Definition chapter for definition of a wait step): Role (standard role) Object of the organizational model Note : WS Types only allow Roles and Containers without applying OSS 93158. If a default role is specified at the task level, entries for responsibility in the Workflow step definition can be left blank if the default role is adequate. 1.50 RULE BASICS - WORKFLOW

EXAMPLE Example of how a rule resolution could be used in an invoice verification clerk Workflow. Design requirements : Runtime 1.51 RULE DEFINITION IN AN ACTIVITY STEP TYPE - WORKFLOW Various options to create standard rules: Responsibility (Pure configuration no ABAP coding)

Evalution paths (Pure configuration no ABAP coding) Organizational data (Pure configuration no ABAP coding) Functions to be executed – ABAP Code – Function Module Essentially, there are 4 types of rules that you can use in the Activity step type. The rule using organizational attributes is not used in the SAP R/3 component. Tree of the four rules only require system settings; for the fourth solution, a customer-specifc function module must be defined in the system. Organizational data : Rules using organizational data require a SAP organizational object type in the system. Table T7791 contains the delivered SAP organizational object types and information about which organizational object types can be linked to them. Within the object type processed by the Workflow, one element must refer to this SAP organizational object type. The SAP organizational object type is linked to agents using organizational units, positions or jobs. For more information, see the appendix of this folder or the Workflow documentation. The key word is Organizational object. Responsibilities : As of Release 4.0, you can define rules using responsibilities. In the rule container, you define variables that are flled with values at runtime. You also define value ranges for these variables and assign agents to the different value ranges. 1.52 RULE DEFINITION WITH RESPONSIBILITY: EXAMPLE

Example: 99900154 The two administrators are responsible for employee queries in a medium-sized company. Mr. Smith is responsible for employees with surnames from A to K Ms. Jones is responsible for employees with surnames from L to Z

To create a rule with responsibilities, you must enter the following: What happens at runtime? The rule you just defined is called and it receives a value for element. If the current value is between A and K, Mr. Smith receives the work item. If the current value is between L and Z, Ms. Jones receives the work item. In general, you can also define more than one rule with responsibilities in the rule container and create any combinations for value ranges with agents. 1.53 EVALUATION PATH AS RULE

Here are the basic steps:

1.54 ROLE RESOLUTION A role defines rule by which selected agents can be determined at runtime through role resolution. Rule resolution restricts the number of possible agents.

When a default role is specified at the task definition level, or a standard role is specified for responsibility at the workflow step level, role resolution occurs at runtime. For example, a default role for approving a vacation request would be the supervisor of the user submitting the request. At runtime, role resolution would determine, from the set of all possible supervisors, the specific supervisor of the user submitting the request. This specific supervisor would be the selected agent for approving the request. A role defines rules by which selected agents can be determined at runtime through role resolution. Role resolution restricts the number of possible agents. Role resolution is performed through function modules or organizational objects. See section the Creating Roles chapter in the Programming section for details on how to build a role. The input values to the role resolution function module consist of role parameters. Role parameters create elements in the role parameter container. At runtime, the role container is filled with all necessary information through the binding definition from the workflow container or task container to the role container. The role container is a parameter of the roles function module. The role resolution process executes the function module. The algorithm in the function module determines selected agents and inserts them in an internal table that is a parameter of the function module. This is returned directly to the workflow runtime system. 1.55 ROLE RESOLUTION WITH FUNCTION MODULES: EXAMPLE Role resolution with function module should be done only for complex criteria Here are the basic steps: A function module with the following interface is created

Create a rule setting the type 'Function to be executed'. Enter the created function module name. Create container elements. Example:20000116, 50000133 The function module of the role is executed at runtime by the workflow runtime system. The role parameters are passed to the function module as a container. The role container is one of the table parameters of every role function module. The values of the role container must be read in the function module using macros. The selected agents resulting from role resolution are stored in the table SWHACTOR. SWHACTOR is also one of the table parameters of the function module.

The structure SWHACTOR that holds the resulting selected agents consists of: OTYPE: The 2-character ID of the organizational management object type. Examples include: OBJID: The 12-character unique identifying key of the organizational management object type. These values can be determined by turning the key on when viewing the organizational plan. 1.56 EXECUTION OF A ROLE RESOLUTION VIA ORGANIZATIONAL OBJECTS Via organizational objects: Role resolution utilizing organizational data analyses the assignment of an organizational object (plant, laboratory, MRP controller, planner group, shipping point, sales office) to a position or organizational unit.

1.57 TASKS: POSSIBLE AGENTS & DEFAULT ROLES

As we said before, work items are the runtime representation of steps in a workflow. Steps reference tasks. Tasks are activities which create, delete, change or otherwise affect one or more business objects. Tasks can be single-step or multi-step. We will discuss these in more detail in the chapter called Tasks. Agents are an important part of tasks. Possible agents (capable executors of the task) must be assigned to the single-step task. (Within the task definition, Additional data—Agent assignment -—Maintain.) These are the agents drawn from the organizational plan who are qualified to perform the task. Selected agents are derived from all possible agents assigned at the single-step task level. The selected agents can be the same as the possible agents, or a subset of the possible agents derived from a default role. Restriction of the possible agents to a subset is optional. Processing agents, deadline agents, and notification agents can all be specified as subsets of the possible agents using the default role of the task definition. ExAMPLE: Example of how a rule resolution could be used in an invoice verification clerk workflow. Design requirements: All clerks working in this department are assigned to a specific customer group. At runtime, they should only receive invoices from these customers. Each clerk has a pre-defined personal transaction limit. If the invoice exceeds this limit, this clerk is not allowed to process the invoice. Runtime: The two import parameters for the rule resolution ("Customer name, invoicing amount) determine that the work item should be sent to the three agents circled in red. Only those three recipients will receive this work item in their worklist. The first user to execute the work item at runtime will block access to this work item. No other user will then be able to access this work item. The

work item will disappear from the worklist of the other two users when they refresh their worklist. After the first agent has completed the work item, it will disappear automatically from his or her worklist the next time the screen is refreshed. 1.58 HOW ARE SELECTED AGENTS DETERMINED WITH AND WITHOUT A DEFAULT ROLE

As we said on the previous page, one-way selected agents can be determined is at the task level is via a default role. A role defines rules by which selected agents can be determined at runtime. Use the menu path: Definition tools Standard roles to list all the available roles, their function modules, and parameters. A default role can be established in the definition of the single-step task to determine selected agents (from the pool of possible agents) at runtime. (Within the task definition, click on the Default roles push-button). If no default role is indicated at this level, all possible agents are selected to process this task at runtime. A default role is helpful if a single-step task is started by a triggering event. In this event, selected agents can be drawn from the possible agents. If default roles are specified, it may require a binding definition from the task container to the role parameter container. (See the chapter on Containers, Dataflow and Binding). Another way selected agents can be determined at the task level is by designating the task a general task — meaning all users in the system are selected agents unless a default role is assigned. 1.59 HOW ARE SELECTED AGENTS DETERMINED WITH A WF AGENT Another way selected agents can be established is via agent assignments. Responsibility assignments can be assigned for a workflow step. Responsibility is specified at the workflow step level within the workflow definition. Responsibilities defined here override the default role established at the task level.

When responsibility assignments are in place, changes can be made to the organizational plan, and these changes will automatically take effect on the agents selected in a workflow definition without having to change the workflow definition.

Responsibility assignments for activity steps and user decision steps can be determined by selecting one of the responsibilities below. Processing agents, deadline agents, and notification agents can all be specified with the following designations (only deadline and notification agents can be specified for a wait step. See Workflow Definition chapter for definition of a wait step): Note: WS Types only allow Roles and Containers without applying OSS 93158. If a default role is specified at the task level, entries for responsibility in the workflow step definition can be left blank if the default role is adequate. 1.60 ORGANIZATIONAL STRUCTURE BUSINESS SCENARIO An organizational plan in SAP describes the organizational structure of a company. The workflow system finds the agents of the individual tasks by evaluating the organizational plan. The functions to create and maintain organizational plans are part of the Personnel Planning and Development (PD) part of the SAP HR module. You must connect this organizational structure to the workflow. 1.61 ORGANIZATIONAL MANAGEMENT Organizational units contain positions, occupied by employees. Jobs are abstract descriptions of task assignments. Positions can be linked to jobs. They inherit all the tasks assigned to that job. Users: A user is an SAP logon user ID. It thus represents a single person. Persons: A person is a specific employee created in the HR module. Workflow tasks can be assigned to organizational units, positions, jobs or users. The workflow system uses organizational structure to route work items to the correct recipients. Any organizational plan consists of five kinds of classifications: Generally, one organizational unit forms the root of the hierarchy and contains all other organizational units as subordinates. Positions: A position represents a slot in an organizational unit filled by a single person, or shared among two or more people. Two examples are H/R Manager and A/P Clerk. Jobs: A job is a more general description of a position. A single job can describe multiple positions across multiple organizational units. There is, therefore, a one-to-many relationship between jobs and positions. Users: A user is a SAP logon user ID. It represents a single person. Persons: A person is a specific employee created in the HR module. In order for a person to be usable in a Workflow scenario, we must assign the person to a user, since only a user has access to the SAP mail system. This is configured as part of the HR implementation. 1.62 CREATE ORGANIZATIONAL PLAN The first step in simple maintenance involves creating the root organizational unit. Once this organizational unit has been created, create the appropriate lower-level organizational units. Organizational units and jobs may be created in any order, but they must exist before the related positions are created. Jobs may exist in the job index, or they may be created once the model contains an organizational unit. Positions are created after the corresponding jobs have been created in the job index. Caution: In the SAP R/3 Release 4.6B component, you must define a position first. You can then create the job with reference to the position.

Holders are assigned to positions, not to jobs. The next slide shows the link between workflow tasks and organizational objects. The maintenance of SAP Organizational Management is available as a Basis component. The Create Organizational Unit icon allows you to create and maintain the organizational structure for your organizational plan. The Create Position icon allows you to create the positions again as part of your organizational plan. The Tasks function allows you to create, maintain and view assignments for jobs, positions, and users. 1.63 ASSIGNMENT WORKFLOW TASK ORGANIZATIONAL OBJECTS

1.64 TRANSACTION – PPOCW

1.65 EVENT TRACE- SWEL

1.66 EVENT TRACE - SWELS The Event trace needs to be switched on for the event to be visible in the trace

1.67 EVENT LOG DETAILS

1.68 WORKFLOW LOG-SWI2_FREQ

The agents who have participated in the workflow are displayed here. For all the background steps — agents are WF-BATCH.

The screen displays the status of individual Workflow instance for the selected workflow.

1.69 WORKFLOW LOG-SWI2_FREQ – NORMAL VIEW

1.70 AGENTS INVOLVED IN WORKFLOW The agents who have participated in the workflow are displayed here. For all the background steps — agents are WF-BATCH

1.71 WORKFLOW LOG-SWI2_FREQ – GRAPHICAL VIEW The green line indicated in which step the workflow is currently lying.

1.72 WORKFLOW LOG-SWI2_FREQ- TECHNICAL VIEW

1.73 SOME IMPORTANT JOBS – WORKFLOW 1.74 WORKFLOW EXPLORER – SWDM

1.75 TEST YOUR KNOWLEDGE – WORKFLOW 1.76 WORK ITEM TYPES – WORKFLOW Work item types displayed in the Business Workplace 1.77 BUSINESS OBJECT REPOSITORY (BOR)

BOR is a client-independent directory of all defined object types. Each object type is assigned to a development class and, therefore, indirectly to an application component. 1.78 SOME COMMON BUSINESS OBJECTS AND INTERFACES 1.79 OBJECT TYPE – RELEASE STATUS & WORKFLOW

The modeled status is the only status in which execution is not possible. Customers should, however, only use components with the released status. The release information should be noted when a component's status changes to obsolete. 1.80 SUBTYPE & WORKFLOW Subtype The subtype inherits all attributes, methods and events of the supertype and is open for new customer-specific attributes, methods and events. The key fields of the supertype and substype must be identical. This means that any methods and attributes defined on the parents can be executed and accessed on the chiled.

Reference: SAP AG The additional attributes, methods, and events is needed to do analysis of an existing object type. If this modification is described in a SAPNet note, an user can only make changes directly in an object type provided by SAP. Proceed as follows in order to create a subtype: 1.81 DELEGATION & WORKFLOW

ABAP consultant has been assigned to implement some security measures for the company's online store. It is simple requirement and it articulates the password should be 6 characters long. (Mandatory) The tricky thing here is to find a way to implement functional logic without modifying SAP code considering maintenance cost of SAP future version upgrade. When customers change their passwords, the method CHANGEPASSWORD (in BAPI) on the object KNA1 (Customer) is getting called. To create a subtype of KNA1 and then redefine the CHANGEPASSWORD method adding the ABAP code is to ensure that the password is a minimum of six characters long, it is the main activity here. The consultant just needs to implement the business rules in ABAP once the method is redefined. Use the Business Object Builder to set up a delegation: Basic Menu → Tools → Business Workflow → Development → Definition tools → Business Object Builder → Settings → Delegate Change Mode → New Entries Button Object type: Enter the supertype Delegation type: Enter the subtype Person reponsible: Whoever entered the delegation, that is, whoever is responsible for Customizing Caution:

Do not enter anything into the GUI-specific field. You can create any number of subtypes for one supertype. However, only one of these subtypes can be selected as a delegation type. Testing delegations: Status before delegation: Display the required supertype in the Business Object Builder and select the Test icon. You will not see any attributes, events or methods defined for the subtype. Status after delegation: Display the required supertype in the Business Object Builder and select the Test icon. You will see all of the attributes, events, and methods defined for the subtype and you can test the elements. 1.82 OBJECTS IN THE WORKFLOW

Workflow are usually started using events. The event defined in the BOR then acts as a triggering event. Events can complete workflow steps. In this case, the event is a terminating event. Tasks call the object type methods, and therefore determine the function executed at runtime. You can use attributes in steps (condition, loops, and so on), but you can also use attributes in texts (work item text and the long texts for a task). You can change object type definitions without having to modify workflow definitions or organizational structures. 1.83 BUSINESS OBJECTS – PROGRAMMING AND WORKFLOW Key Features Attribute programming For multiline attribute the structure will look like the following: GET_PROPERTY CHANGING CONTAINER. ......code SWCSETTABLE CONTAINER InternalTable END_PROPERTY. Methods Programming

BEGIN_METHOD CHANGING CONTAINER. .....code END_METHOD. Ex : BEGIN_METHOD display CHANGING CONTAINER. SET PARAMETER ID 'MAT' FIELD object-key-material. CALL TRANSACTION 'MM03' AND SKIP FIRST SCREEN. END_METHOD. 1.84 WRITING/READING CONTAINER ELEMENTS DEFINED AS FIELD VALUES ֊ WORKFLOW

An object reference can be created in method using SWCCREATEOBJECT macro BEGIN_METHOD CHANGING CONTAINER. .....code data : user type swc_object. SWCCREATEOBJECT user 'User' . SWCGETPROPERTY user 'Name' . ...code END_METHOD. Exception is methods that can be raised using the macro EXITRETURN EXITRETURN Where is the exception number defined for method Macros for Method Exceptions 1.85 CONTAINER MACROS & WORKFLOW

Definition and Initialization SWC_CONTAINER SWCCONTAINERCREATE If you are creating function modules for event creation, you will need to create, initialize and release containers. In an object type implementation program, this is unnecessary. A container called "CONTAINER" is created automatically and the macros to manipulate the values of the container elements are at your disposal through the include. The following macro instructions define and control containers: A container cannot be edited after it has been released. Throughout the remainder of this chapter, assume that unless you are coding in an object implementation program, you will need to incorporate the includes or and use the appropriate macros to declare and initialized containers before using the other macros to write values to containers or read values from them. 1.86 SINGLE AND MULTISTEP TASKS AND WORKFLOW

Single-step Tasks Single-step tasks describe elementary business activities. Single-step tasks operate on an object and refer to one object method each. Single-step tasks are linked to their possible and permitted agents whose organizational assignments are described in the organizational plan of the enterprise. Executable single-step tasks are represented by work items at runtime. Workflow Definition - Multistep Tasks A workflow definition has a modular structure consisting of individual steps which are linked together. The multistep tasks form the business framework for a workflow definition and each references one workflow definition. A step in a workflow definition can be an activity. An activity always refers to one task (= single-step task or multistep task).

An activity with one simple triangle refers to a task,

An activity with three triangles refers to a workflow (subworkflow). 1.87 TASK DEFINITION – SYNCHRONOUS AND ASYNCHRONOUS METHODS AND WORKFLOW

A terminating event applies to one instance of a task, that is, to one specific work item. The work item in turn refers to one specific object for the object type. You must specify a connection to this object for the terminating event. Example: A head of department has four work items for vacation approval. The request numbers are 2000 (work item 1), 2001 (work item 2), 2002 (work item 3) and 2003 (work item 4). Applicant 2002 deletes his entry. This means that the work item in the inbox is no longer required and must be deleted. The Request deleted terminating event must now be generated for object 2002. The existing work item is completed automatically if the Deleted event is triggered n the system. The event must refer to the object on which the work item is based. The object is specified in the WIOBJECT_ID element. 1.88 DEFINING A TASK & WORKFLOW

First: Assign the business object type method to your task. Second: Assign the maximum number of possible agents. (Entry under the Additional data -> Agent assignment -> Maintain menu option). You can refer to the organizational model or to an activity group. Create: Select the task, Agent assignment menu option -> Create, select and specify the required organizational object. The task can also be a general task, that is, each SAP user is a possible agent.

Create: Select the task ,Attributes button, General Task indicator. Third: Define the work item text and required long texts for the task. You can insert workflow interface variables that will be triggered with the current data at runtime. If an asynchronous method call is used for the task, the method does not return confirmation of completion to the calling system when it is completed. Accordingly, the work item is not completed. An asynchronous method must make the notification of completion known using an event. This event has to be entered as a terminating event for the task. Triggering events are only required if the task is to be started independently of the workflow definition. You will find these types of events in the SAP System when handling IDOC errors, for example. 1.89 SETTING FOR TASKS - WORKFLOW

Confirm for background task, end of processing cannot be selected. Customer service SAP phone scenario To a customer, a call needs to be placed by a sales service clerk. To a telephone number (attached to the current customer object for the workflow) the workflow calls get dialed. The sales clerk can talk to the customer while viewing the important customer data on the screen at the same time once the connection gets established. Your company is getting called by Customer The customer is asked by telephone service tool to enter the customer contract number. The important customer data is getting collected by the SAP System and a workflow is getting started. The next available customer service clerk starts the work item. His or her telephone is now connected to the customer and the customer data is displayed on her or his screen. The 'Executable with SAP forms' indicator refers to tasks which, when executed, should display the data from the container in a form created externally (using Visual Basic, Lotus Notes, Outlook Editor, for example). 1.90 WORK ITEM TEXT - WORKFLOW Title of workitem in the Business Workplace First create the workitem text and position the cursor to include a variable Choose the Insert variable icon under the workitem text Example Processes request from &WIObject_ID.CreatedBy& 1.91 WORKFLOW DEFINITION STEPS Several individual steps constitute Workflow definition. The step type should be specified first while creating a step in the workflow definition. There are:

Condition

Multiple condition Until Loop

Fork

Send mail

Container operations Event Creator

WAIT for event 1.92 TYPES OF CONTAINERS - WORKFLOW

There are five types of containers used in SAP Business Workflow. The task container always contains an element that can save the reference to the object to be processed in the relevant single-step task (WIObjectID). It also contains the "WIActual Agent" element, which is the agent who actually executed the work item. For synchronous tasks with a defined result parameter, the 'WIResult' element exists, which can save the result of the basic object method. The workflow container always contains an element that can store the user name of the initiator of the current workflow (WFInitiator). For most workflows you must create a new element in the workflow container. To do this, you can either accept the SAP proposals, or you can create your own element. For example, you have to provide a storage element for the main object of your process. The event container always contains an element that can save the (object) reference to the object whose change of status is made known using the event 'EVTObject' element. It also always contains an element with the name of the user responsible for changing the status of the object ('EVTCreator'). The rule container contains the elements required as an entry for the rule resolution at runtime. If you define a default rule for the task, the binding can also occur from the task in the rule. The method container contains elements that are import parameters in connection with the method execution. You use macros to make the values available in the method. 1.93 WORKFLOW CONTAINER The workflow container contains workflow-specific system variables and other elements which are defined explicitly. As part of the definition of the workflow task, the import and export parameters of the workflow are defined as elements of the workflow container.

When the workflow is defined in the workflow editor, elements can also be added to the workflow container. These elements are then local variables within a workflow definition and can be used, for example, to set up a counting loop.

1.94 TASK CONTAINER Each task container already contains the workflow system variable and any additional elements for the method parameters of the referenced object method. You have to add additional elements to the task container for additional values are required for variable replacement in the work item text or in the long texts.

1.95 OTHER TYPES OF CONTAINER – WORKFLOW Event Parameter Container Contains an element which can take the (object) reference to the object whose change of status is announced via the event. Rule Parameter Container Contains the elements required as input in connection with the rule resolution to be run at runtime.

Method Parameter Container Contains elements which will be required as import and export parameters in connection with the method execution. 1.96 BINDING – WORKFLOW A binding is simply the art of pouring selected container elements from one container into another. The binding editor is available when defining: Workflow definitions Triggering events Workflow steps Workflow steps ( Standard roles/ Object methods with parameters) The binding editor always references the container to receive the application data. Binding definitions can reference: Constants Variables (container elements) System fields 1.97 CONTAINER & DATAFLOW - WORKFLOW

Data flows between the workflow components as follows: 1.98 WHAT IS A CONTAINER

A container is a table like structure for collecting and storing data within the workflow and its components. A container definition defines the structure of the data values to be stored in the container instance. A container definition is assigned to the following workflow components: Container definitions are defined in the various workflow components by a container editor. A container instance is a runtime representation of a container definition. It refers to field values, multiline field values or object types. Application data is not stored directly in the container instances. The data utilized within a workflow is managed by the application and stored in the database. Data assignment to a container element is carried out by: 1.99 DEFINING CONTAINER ELEMENTS

A container editor allows individual container elements to be created and edited. z Functions available in the container editor include: Element names must begin with a letter. The element name can be automatically assigned by the ABAP/4 Dictionary field name. 1.100 SOME STANDARD CONTAINER ELEMENTS WIOBJECTID: At runtime, the task container element _WIOBJECTID contains the reference to the object which is processed in the object method. WIRESULT: If the customer task/ standard refers to a synchronous object method, the result of the method is available in the element of the task container. EVTOBJECT: This reference to the object initiating the event allows you to access the attributes of this object. 1.101 SOME KEY FEATURES Key Features: Attribute programming For example: GET_PROPERTY Total CHANGING CONTAINER. DATA: Price TYPE Zprice, Qty TYPE Zqty. IF object-total is initial. SWCGETPROPERTY self 'Price' Price. SWCGETPROPERTY self 'Quantity' Qty. Object-Total = Price * Qty. ENDIF. SWCSETELEMENT CONTAINER 'Total' object-total. END_PROPERTY.

1.102 CONTAINER MARCOS – WORKFLOW Definition and Initialization SWC_CONTAINER Reading and Setting Elements SWCGET\SETELEMENT SWCGET\SETTABLE If you are creating function modules for event creation, you will need to create, initialize and release containers. In an object type implementation program, this is unnecessary. A container called CONTAINER is created automatically and the macros to manipulate the values of the container elements are at your disposal through the include. The following macro instructions define and control containers: Throughout the remainder of this chapter, assume that unless you are coding in an object implementation program, you will need to incorporate the includes or and use the appropriate macros to declare and initialize containers before using the other macros to write values to containers or read values from them. 1.103 WRITING/READING CONTAINER ELEMENTS DEFINED AS FIELD VALUES

1.104 MACROS FOR OBJECT DEFINITION AND DECLARATION Declaration: Data: TYPE SWC_OBJECT Example DATA: Customer TYPE SWC_OBJECT Definition: SWCCREATEOBJECT Example SWCCREATEOBJECT Customer 'KNA1' customer_number 1.105 WORKFLOW AND ALE Here is an example scenario for Material master Error handling:

Workflow and ALE Error Notification Active Monitoring IDOC Processing Notification of successful posting 1.106 WORKFLOW AND ERROR NOTIFICATION

1.107 ACTIVE MONITORING Active monitoring allows specifying threshold values for the state of the system For e.g. threshold can be on the number of IDOCs in error or the time limit. Report Program RSEIDOCA can be executed periodically Selection screen takes as input the threshold values and persons to be notified

When defined, threshold is exceeded Single Step Task TS30200088 is executed 1.108 SETTING UP INBOUND PROCESS VIA WORKFLOW The standard system can be configured to start a WF for an incoming IDOC. Useful when review is essential before posting. Custom SAP does not deliver standard. The settings are: 1.109 NOTIFICATION OF SUCCESSFUL POSTING The ALE/EDI interface can raise events on successful posting of an IDOC. The settings are as follows: 1.110 ALE ERROR HANDLING Necessary Steps: Here is a summary of the necessary steps to enable IDOC error handling: Update Process Code (BD67) to refer to the above-mentioned objects and events To support mass processing: Create new object type as child of IDOCPACKET 1.111 SOME IMPORTANT TRANSACTION CODES / TABLES - WORKFLOW 1.112 WORKFLOW CUSTOMIZING – SWU3

The function Automatic Customizing allows you to maintain SAP Business Workflow standard settings at the touch of a button. Afterwards, using the button Verification workflow, a first test workflow can be started to check the settings. In the Workflow runtime system section, the traffic light icon should always be green.

In the Workflow development environment section, an entry with errors in Number range for customer tasks can be ignored. If the error PD control tables not completely available occurs, start the report RHSOBJCH. Automatic Customizing does not contain either maintenance of the organizational plan, or task-specific customizing, (meaning the assignment between tasks and possible agents). 1.113 WORKFLOW LOG-SWI2_FREQ

The function Automatic Customizing allows you to maintain SAP Business Workflow standard settings at the touch of a button. Afterwards, using the button Verification workflow, a first test workflow can be started to check the settings. In the Workflow runtime system section, the traffic light icon should always be green. In the Workflow development environment section, an entry with errors in Number rangefor customer tasks can be ignored. If the error PD control tables not completely available occurs, start the report RHSOBJCH. Automatic Customizing does not contain either maintenance of the organizational plan, or task-specific customizing, (meaning the assignment between tasks and possible agents). 1.114 MAINTAIN START CONDITIONS FOR WORKFLOW: SWB_COND

1.115 SOME IMPORTANT DIAGNOSIS TRANSACTIONS - WORKFLOW PFTC/SWDD: Task editor/Workflow Builder

SWU3: Verify Workflow Customizing SWEL: Event Log SWE2: Event type linkage SWU0: Event simulation SWI1: Work item list OOCU: Customizing overview SWUE/SWUS: Event/workflow trigger 1.116 SOME IMPORTANT TABLES 1.117 WORKFLOW WITH FUNCTION MODULES AND REPORTS Function Module SWIWORKITEMSOFOBJECTGET The Function Module is used to pick all the workitems generated related to specific Document Number, based on the type of Business Object and Key.

The below function module is used to get all the instances based on the key values. It will also extract all the workitem ID's based on Key fields. SWWWIAGENTS_READ The Function Module is used to get the Agents based on the workitem.

SAPWAPIWORKITEMSTOOBJECT To get all the workitems based on the Business Object and Key. Task Filter can also be set. SAPWAPIWORKITEM_RECIPIENTS, SWIGETUSERS_OFORGUNIT to get the user based on position, organization unit etc. SWWWICONTAINERREAD, SAPWAPIREADCONTAINER: The function Module to read the container based on the workitem ID. SWWWICONTAINER_MODIFY: Modify the container by passing the workitem ID. SWWWIADMIN_COMPLETE: complete the workitem programmatically. SWLSHOWPROCESS_DATA: The function Module to show the Workflow Log. SWUGETDECISION_TEXT to get the user decision text in the report SAPWAPISTART_WORKFLOW (Example in my notes) SWWWISTART_SIMPLE SWWWIEXECUTE_NEW is the function module to execute the background task SWWWISTATUSCHANGENEW is used to change the status of workitem to ready from any status Tables: SWWWIHEAD: Workflow Runtime: Header Table for All Work Item Types SWWUSERWI: Current workitems assigned to a User Swwloghist: workflow log history table 1.118 STANDARD RULES A rule container is defined for each rule. The rule parameters determine which information is required for the rule resolution to be executed at runtime. If an error occurs during rule resolution, setting the termination indicator for the rule resolution determines how the workflow will continue: Flag is selected: the workflow assumes an Error status and a notification is sent to the workflow administrator. Indicator is not activated: the workflow forwards this work item to ALL possible agents. 1.119 SOME IMPORTANT JOBS SWWDHEX For deadline monitoring SWWERRE For error Monitoring

SWEQSRV For Event Queue Delivery 1.120 SOME WORKFLOW CONCEPTS What is Workflow: Workflow is a tool to automate business process. Workflow can be single step or multiple steps. Single step workflows are Tasks and multiple step workflows are Templates. Workflow determines which tasks are executed, when, under which conditions and by whom. Workflow definition is made up of individual steps. When creating a step in a workflow definition, the step type must be specified first. Specify the step type as Activity here. Activity can be a single step task with basic business functionality. Can be a multi-step task, which reference to a workflow definition. What are the different elements of Workflow: Tasks: Activity in which an object method is carried out. Business Objects: Identifiable specific instances of an object type. Work Item: A work item is an actual representation of a task. Agent: An agent is an executor of a work item. Types of agents: Possible agent Deadline agent Notification agent Methods: Events Containers: Containers are used to store field values, multi-line lists of field values, object references and multi-line lists of object references. All import/export parameters of the workflow tasks/workflow templates are specified as elements of the workflow container. Containers only contain control information for the workflow system. Containers do not contain application business data. Binding: Binding definition executed at runtime. Used for transferring data from one container to another container. Used for assigning values to container elements. Binding is always performed with reference to the elements of a container Data flows between the workflow components as follows:

1.121 AUTOMATIC EMAIL SENDING FUNCTIONALITY IN WORKFLOWS AND CUSTOMIZATION There is a standard SAP Functionality which sends email notification to all approvers of a workflow, when it is pending for their approval. To enable this setting the program – RSWUWFML2 has to be scheduled in the background. However, if you need custom messages to go along with this standard message – It is possible by customizing the standard program. The way this was implemented is – A custom table was created and it was plugged into this standard code with slight modifications. The content which is to be customized – was put in the custom table, from which, data is rendered based on the task id of the workflow. In our case – We wanted End URL to be added to the email – which approver would use to click and login. The sample code and Table structure is given as follows. Never hard code any Text anytime. Always create Text as Text elements or Text IDs.

*&--------------------------------------------------------------------- * *& Report RSWUWFML2 *& *& Enhanced version of RSWUWFML *&--------------------------------------------------------------------- * REPORT zrswuwfml2. DEFINE swutracewrite. swu_tracewriteformsmsg &2 &1 &4 &3 &5 &6 &7 &8 &9. END-OF-DEFINITION. TABLES: swwwihead, " Workflow Runtime: Header Table for All Work Item Types swu_wlscan, " Date and time of last work list scan for R3F transmission rs38l. " Screen fields of the Transaction UNIT

Parameters *

Instance data SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-t06. PARAMETERS: pjobsuf LIKE swuwlscan-curr_numb DEFAULT '2'. " Sequential number (max.value 9) '1' is the suffix for SAPforms, so here we choose '2' as default. SELECT-OPTIONS: ptasks FOR swwwihead-wirh_task. " Task ID PARAMETERS: p_langu LIKE t100-sprsl. " Language Key PARAMETERS: p_new TYPE charl AS CHECKBOX. " New of type CHAR1 PARAMETERS: p_psubst TYPE charl AS CHECKBOX. " Psubst of type CHAR1

SELECTION-SCREEN END OF BLOCK b1. How many messages should be sent? SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-tOl. PARAMETERS: x_nl4all RADIOBUTTON GROUP gl USER-COMMAND chck, " For each work item one message is sent x_l4all RADIOBUTTON GROUP gl DEFAULT 'X'. " One message per work item SELECTION-SCREEN END OF BLOCK b2. With executable attachment (Shortcut) SELECTION-SCREEN BEGIN OF BLOCK b3 WITH FRAME TITLE text-t02. PARAMETERS: xscinb AS CHECKBOX USER-COMMAND chck, " shortcut for inbox xscdis AS CHECKBOX USER-COMMAND chck, " shortcut for display xscexe AS CHECKBOX USER-COMMAND chck. " shortcut for execute SELECTION-SCREEN END OF BLOCK b3. Textlines for standard notification text SELECTION-SCREEN BEGIN OF BLOCK b4 WITH FRAME TITLE text-t03. PARAMETERS: psnac LIKE sy-msgid DEFAULT 'SWU_NOTIF'. " ABAP System Field: Message ID PARAMETERS: psnan LIKE sy-msgno DEFAULT '00l'. " ABAP System Field: Message Number PARAMETERS: pprol LIKE dokhl-object DEFAULT 'SWUNOTIF_PROLOGl'. " Documentation Object PARAMETERS: pepil LIKE dokhl-object DEFAULT 'SWUNOTIF_EPILOGl'. " Documentation Object SELECTION-SCREEN END OF BLOCK b4. shortcut parameters SELECTION-SCREEN BEGIN OF BLOCK b5 WITH FRAME TITLE text-t07. PARAMETERS: p_logon TYPE text50. " Text Field SELECTION-SCREEN END OF BLOCK b5. user exits SELECTION-SCREEN BEGIN OF BLOCK b8 WITH FRAME TITLE text-t08. SELECT-OPTIONS: p_expre FOR rs38l-name. " Name of Function Module SELECT-OPTIONS: p_exadr FOR rs38l-name. " Name of Function Module SELECTION-SCREEN END OF BLOCK b8. Parameters for a single run

SELECTION-SCREEN BEGIN OF BLOCK b6 WITH FRAME TITLE text-t04. PARAMETERS: p_fromd LIKE sy-datum, " ABAP System Field: Current Date of Application Server p_fromt LIKE sy-uzeit, " ABAP System Field: Current Time of Application Server " only work items created after this date/time " are considered " these parameters overrule the table settings p_user LIKE sy-uname. " ABAP System Field: Name of Current User " only messages for work items in this user's inbox " are forwarded SELECTION-SCREEN END OF BLOCK b6. Protocol SELECTION-SCREEN BEGIN OF BLOCK b7 WITH FRAME TITLE text-t05. PARAMETERS: xerrtr RADIOBUTTON GROUP g2 DEFAULT 'X', "trace errors only xalwtr RADIOBUTTON GROUP g2. "trace everything SELECTION-SCREEN END OF BLOCK b7.

Declarations *

INCLUDE: rswuincl. " workflow constants INCLUDE: rswugdat. " for trace writing > 3.1 TYPES: tsolisti1tab TYPE TABLE OF solisti1. " SAPoffice: Single List with Column Length 255 TYPES: BEGIN OF tuserdata, uname TYPE syuname, " User Name langu TYPE sylangu, " Language Key email TYPE string, logon_langu TYPE sylangu, " note 849251 sent TYPE xfeld, " Checkbox END OF tuserdata. TYPES: BEGIN OF t_substitution, user TYPE syuname, " User Name substitute TYPE syuname, " User Name profile TYPE hrrepprf, " Substitute Profile END OF t_substitution. TYPES: BEGIN OF twidata,

wiid LIKE swwwihead-wiid, " Work item ID tclass TYPE hrtaskcl, " Classification of Tasks END OF twidata. TYPES: tuserdatatab TYPE TABLE OF tuserdata. TYPES: tsubstitutiontab TYPE TABLE OF tsubstitution. TYPES: sopcklsti1_tab TYPE TABLE OF sopcklsti1. " SAPoffice: Description of Imported Object Components CONSTANTS: cdocuiddialogtext LIKE dokhl-id VALUE 'DT', " Document class cdocutyp_e LIKE dokil-typ VALUE 'E', " Documentation type cactiondisplay TYPE char40 VALUE 'DISPLAY', " Action_display of type CHAR40 cactionexecute TYPE char40 VALUE 'EXECUTE', " Action_execute of type CHAR40 cescunix TYPE c VALUE 'U', " Esc_unix of type Character ccomtype_int TYPE sosndart VALUE 'INT', " Transmission Method (Fax, Telex, ... ) cpdotype_usr LIKE swhactor-otype VALUE 'US'. " Object Type * miscellaneous DATA: l_crlf(2) TYPE c. " Crlf(2) of type Character DATA: BEGIN OF crlf, x(1) TYPE x VALUE '0D', " X(1) of type Byte fields y(1) TYPE x VALUE '0A', " Y(1) of type Byte fields END OF crlf. DATA ldynpvalu TYPE doku_obj. "dynfieldvalue. Send options DATA: BEGIN OF s_opt, one4all, " one message for all work items shortcut_inbox, " shortcut for opening the inbox shortcut_display, " shortcut for WI display shortcut_execute, " shortcut for WI execute no_shortcuts, " no shortcuts at all END OF s_opt. Scheduling data DATA: lfromdate LIKE sy-datum, " ABAP System Field: Current Date of Application Server lfromtime LIKE sy-uzeit, " ABAP System Field: Current Time of Application Server ltodate LIKE sy-datum, " ABAP System Field: Current Date of Application Server ltotime LIKE sy-uzeit, " ABAP System Field: Current Time of Application Server lfromtstamp TYPE timestampl, " UTC Time Stamp in Long Form (YYYYMMDDhhmmssmmmuuun) ltotstamp TYPE timestampl, " UTC Time Stamp in Long Form

ltotstamp TYPE timestampl, " UTC Time Stamp in Long Form (YYYYMMDDhhmmssmmmuuun) lsetlastrun LIKE sy-binpt, " Whether or not to treat this " as a full run and set the last-run timestamp. lsystemtimezone TYPE sy-zonlo. " ABAP System Field: Time Zone of Current User Work item data RANGES tasksel FOR swwwihead-wirh_task. " Task ID DATA: lt_users LIKE swhactor OCCURS 0 WITH HEADER LINE, " Rule Resolution Result ltwidata TYPE twidata OCCURS 0 WITH HEADER LINE, lttasktab LIKE swhactor OCCURS 0 WITH HEADER LINE, " Rule Resolution Result l_uname LIKE soud-usrnam, " SAPoffice user name lsendwiid LIKE swwwihead-wiid. " Work item ID Mail data DATA: lsaddress TYPE tuser_data, ltuseraddresses LIKE sousradri1 OCCURS 0 WITH HEADER LINE, " SAPoffice: Connecting structure between user and address litemssent, lproxyemail TYPE swu_prxadr, " SAP Forms: Proxy mail address llangudoc LIKE t100-sprsl. " Language Key text handling DATA: ltextprolog TYPE string, ltextepilog TYPE string, l_body TYPE string. user data DATA: ltuserdata TYPE TABLE OF tuserdata, wauserdata TYPE tuserdata. Error and trace handling data DATA: lmsgv1 LIKE balm-msgv1, " Message Variable lolog TYPE REF TO clswn_log, " WF Notif: Service Class for Logs lmsgtext(100) TYPE c. " Msg_text(100) of type Character user exit data RANGES rtexitprep FOR rs38l-name. " Name of Function Module RANGES rtexitaddr FOR rs38l-name. " Name of Function Module General purpose data DATA: l_count LIKE sy-index, " ABAP System Field: Loop Index

l_tabix LIKE sy-tabix, " ABAP System Field: Row Index of Internal Tables lmailssent TYPE i. " Mails_sent of type Integers Table for substitution DATA: BEGIN OF g_substitutions OCCURS 0, " global variable user LIKE sy-uname, " ABAP System Field: Name of Current User substitute LIKE sy-uname, " ABAP System Field: Name of Current User profile TYPE hrrepprf, " Substitute Profile END OF g_substitutions. DATA: l_subrc TYPE sysubrc. " Return Code DATA: lnoclass TYPE hrtask_cl. " Classification of Tasks DATA: lt_77ro TYPE TABLE OF t77ro. " Definition of Proxy Profiles DATA: wa_77ro TYPE t77ro. " Definition of Proxy Profiles Header definition DATA: hwiheader LIKE swwwihead, "#EC NEEDED lswiheader LIKE swwwihead. " Workflow Runtime: Header Table for All Work Item Types

Initialize send options *

AT SELECTION-SCREEN OUTPUT. check the combination l4all/collection mail IF NOT x_l4all IS INITIAL. CLEAR xscdis. CLEAR xscexe. xscinb = 'X'. deactivate the radio-buttons LOOP AT SCREEN. IF screen-name = 'XSCDIS' OR screen-name = 'XSCEXE' OR screen-name = 'P_EPIL'. screen-input = 0. MODIFY SCREEN. ENDIF. " IF screen-name = 'XSCDIS' OR ENDLOOP " LOOP AT SCREEN ELSE. " ELSE -> IF NOT x_l4all IS INITIAL re-activate the radio-buttons LOOP AT SCREEN.

IF screen-name = 'XSCDIS' OR screen-name = 'XSCEXE' OR screen-name = 'P_EPIL'. screen-input = l. MODIFY SCREEN. ENDIF. " IF screen-name = 'XSCDIS' OR ENDLOOP " LOOP AT SCREEN ENDIF. " IF NOT x_l4all IS INITIAL do not alter fields if at least one field has been changed IF pprol NP 'SWUNOTIF*' OR psnac NP 'SWU_NOTIF*' OR p_epil NE space AND pepil NP 'SWUNOTIF*'. customer has modified ELSE. " ELSE -> IF pprol NP 'SWUNOTIF*' OR switch the default values IF x_l4all = 'X'. IF psnac CP 'SWU_NOTIF*'. psnan = '001'. ENDIF. " IF psnac CP 'SWU_NOTIF*' IF xscinb IS INITIAL. pprol = 'SWUNOTIF_INBOX'. ELSE. " ELSE -> IF xscinb IS INITIAL pprol = 'SWUNOTIF_INBOX2'. ENDIF. " IF xscinb IS INITIAL p_epil = space. ELSE. " ELSE -> IF x_14all = 'X' psnan = '002'. pprol = 'SWUNOTIF_PROLOG1'. IF xscinb = 'X' OR xscdis = 'X' OR xscexe = 'X' . pepil = 'SWUNOTIF_EPILOG2'. ELSE. " ELSE -> IF xscinb = 'X' OR xscdis = 'X' OR xscexe = 'X' pepil = 'SWUNOTIF_EPILOG1'. ENDIF. " IF xscinb = 'X' OR xscdis = 'X' OR xscexe = 'X'

ENDIF. " IF x_14all = 'X' ENDIF. " IF pprol NP 'SWUNOTIF*' OR AT SELECTION-SCREEN ON p_prol. IF NOT p_prol IS INITIAL. CALL FUNCTION 'SWFDOCUMENTATIONCHECK' EXPORTING docuobject = pprol EXCEPTIONS documentationnotfound = 1 OTHERS = 2. IF sy-subrc 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. " IF sy-subrc 0 ENDIF. " IF NOT p_prol IS INITIAL AT SELECTION-SCREEN ON p_epil. IF NOT p_epil IS INITIAL. CALL FUNCTION 'SWFDOCUMENTATIONCHECK' EXPORTING docuobject = pepil EXCEPTIONS documentationnotfound = 1 OTHERS = 2. IF sy-subrc 0. ENDIF. " IF sy-subrc 0 ENDIF. " IF NOT p_epil IS INITIAL AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_prol. PERFORM getdynprovalue USING 'P_PROL' CHANGING ldynpvalu. CALL FUNCTION 'DOCUVALUEREQUEST' EXPORTING id = cdocuiddialogtext object = ldynpvalu LANGU = SY-LANGU typ = cdocutyp_e FORMAINTAIN = 'X' fordisplay = 'X'

WINDOW_TITLE = IMPORTING valueobject = pprol. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_epil. PERFORM getdynprovalue USING 'P_EPIL' CHANGING ldynpvalu. CALL FUNCTION 'DOCUVALUEREQUEST' EXPORTING id = cdocuiddialogtext object = ldynpvalu LANGU = SY-LANGU typ = cdocutyp_e FOR_MAINTAIN = 'X' for_display = 'X' WINDOW_TITLE = IMPORTING valueobject = pepil. START-OF-SELECTION. *- assign crlf. Unfortunately this is different in 4.6 *- and unicode systems l_crlf = crlf. lcrlf = clabap_charutilities=>crlf. Use the task list as a selection criterion if necessary. IF task_sel[] IS INITIAL. tasksel[] = ptasks[]. ENDIF. " IF task_sel[] IS INITIAL Use given language or default language IF p_langu IS INITIAL. llangudoc = sy-langu. ELSE. " ELSE -> IF p_langu IS INITIAL llangudoc = p_langu. ENDIF. " IF p_langu IS INITIAL Set the send options. IF NOT x_14all IS INITIAL. s_opt-one4all = 'X'. ENDIF. " IF NOT x_14all IS INITIAL

IF xscinb IS INITIAL. sopt-shortcutinbox = 'X'. ENDIF. " IF xscinb IS INITIAL IF xscdis IS INITIAL. sopt-shortcutdisplay = 'X'. ENDIF. " IF xscdis IS INITIAL IF xscexe IS INITIAL. sopt-shortcutexecute = 'X'. ENDIF. " IF xscexe IS INITIAL IF xscinb IS INITIAL AND xscdis IS INITIAL AND xscexe IS INITIAL. sopt-noshortcuts = 'X'. ENDIF. " IF xscinb IS INITIAL AND user exits IF rtexitprep[] IS INITIAL. rtexitprep[] = p_expre[]. ENDIF. "IF rtexitprep[] IS INITIAL IF rtexitaddr[] IS INITIAL. rtexitaddr[] = p_exadr[]. ENDIF. " IF rtexitaddr[] IS INITIAL *- establish trace lolog = clswnlog=>getinstance( ). lolog->createlog( i_subobject = 'NOTIFICATIONS' ). *- trace the selection options MESSAGE s0l5(swu_notif) " Selection Setting: &l = &2 WITH 'pjobsuf' pjobsuf "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). LOOP AT task_sel. MESSAGE s0l5(swu_notif) " Selection Setting: &l = &2 WITH 'ptasks' tasksel-low "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ).

ENDLOOP. " LOOP AT task_sel LOOP AT rtexitprep. MESSAGE s0l5(swu_notif) " Selection Setting: &l = &2 WITH 'pexpre' rtexit_prep-low "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDLOOP " LOOP AT rtexitprep LOOP AT rtexitaddr. MESSAGE s0l5(swu_notif) " Selection Setting: &l = &2 WITH 'pexpre' rtexit_addr-low "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDLOOP " LOOP AT rtexitaddr IF xscinb IS NOT INITIAL. MESSAGE s0l5(swu_notif) " Selection Setting: &l = &2 WITH 'xscinb' xscinb "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF " IF xscinb IS NOT INITIAL IF xscdis IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'xscdis' xscdis "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF xscdis IS NOT INITIAL IF xscexe IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'xscexe' xscexe "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF xscexe IS NOT INITIAL IF psnac IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'psnac' psnac "#EC NOTEXT

INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF psnac IS NOT INITIAL IF psnan IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'psnan' psnan "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF psnan IS NOT INITIAL IF p_prol IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'pprol' pprol "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF p_prol IS NOT INITIAL IF p_epil IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'pepil' pepil "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF p_epil IS NOT INITIAL IF p_logon IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'plogon' plogon "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF p_logon IS NOT INITIAL IF p_fromd IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'pfromd' pfromd "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF p_fromd IS NOT INITIAL IF p_fromt IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2

WITH 'pfromt' pfromt "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF p_fromt IS NOT INITIAL IF p_user IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'puser' puser "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF p_user IS NOT INITIAL IF xerrtr IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'xerrtr' xerrtr "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF xerrtr IS NOT INITIAL IF xalwtr IS NOT INITIAL. MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'xalwtr' xalwtr "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). ENDIF. " IF xalwtr IS NOT INITIAL

check the sender address

SAPoffice cannot send SMTP e-mail when the current user has no home SMTP address assigned. — note 1596022: SAP Office uses the Default domain to generate — the sender address, if the user does not have a mail address — Due to this: remove the check PERFORM getemailaddress_cam USING sy-uname CHANGING ls_address. report error IF ls_address-email IS INITIAL.

MESSAGE e019(swu_notif) WITH sy-uname INTO lmsgtext. lolog->addmessage( i_probclass = lolog->priotop ). WRITE: / lmsgtext. save the trace lolog->savelog( ). lolog->refreshlog( ). EXIT. ENDIF.

Get the system time zone *

The system time zone is used to convert the scheduling information of the report into a time stamp. CALL FUNCTION 'GETSYSTEMTIMEZONE' IMPORTING timezone = lsystemtimezone EXCEPTIONS customizing_missing = 1 OTHERS = 2. IF sy-subrc 0. report error MESSAGE e020(swu_notif) " No system time zone maintained. Unable to select work items WITH sy-uname INTO lmsgtext. lolog->addmessage( i_probclass = lolog->priotop ). " class WRITE: / lmsgtext. *- save the trace lolog->savelog( ). lolog->refreshlog( ). EXIT. ENDIF. " IF sy-subrc 0

Read the scheduling information *

Read the last date and time the report was run successfully for this job suffix. If the corresponding report parameters are not set and we have not found an entry, swuwlscan-llast_date and swuwlscan-llast_time will be initial, which does not cause any harm. IF p_fromt = space. CLEAR p_fromt. ENDIF. " IF p_fromt = space IF p_fromd IS INITIAL AND p_fromt IS INITIAL AND p_user IS INITIAL. SELECT SINGLE * FROM swuwlscan WHERE currnumb = p_jobsuf. IF swuwlscan-lastts IS INITIAL. lfromdate = swuwlscan-lastdate. lfromtime = swuwlscan-lasttime. ELSE. " ELSE -> IF swuwlscan-lastts IS INITIAL lfromtstamp = swuwlscan-lastts. ENDIF. " IF swuwlscan-lastts IS INITIAL lsetlastrun = 'X'. ELSE. " ELSE -> IF p_fromd IS INITIAL AND lfromdate = p_fromd. lfromtime = p_fromt. ENDIF. " IF p_fromd IS INITIAL AND IF lfromtstamp IS INITIAL. create 'from' time stamp IF lfromdate IS NOT INITIAL OR lfromtime IS NOT INITIAL. CONVERT DATE lfromdate TIME lfromtime INTO TIME STAMP lfromtstamp TIME ZONE lsystemtimezone. IF sy-subrc 0. report error MESSAGE e021(swu_notif) " Error while determining time stamp &1 &2; selection not possible WITH lfromdate lfromtime INTO lmsgtext. lolog->addmessage( i_probclass = lolog->priotop ). " class

WRITE: / lmsgtext. *- save the trace lolog->savelog( ). lolog->refreshlog( ). EXIT. ENDIF. " IF sy-subrc 0 ENDIF. " IF lfromdate IS NOT INITIAL OR lfromtime IS NOT INITIAL ENDIF. " IF lfromtstamp IS INITIAL 'to' time stamp is current time minus 5 seconds to make sure that workitems currently being processed are caught GET TIME STAMP FIELD ltotstamp. ltotstamp = clabaptstmp=>add( tstmp = ltotstamp secs = -5 ). note 929393: enhanced logging MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'from timestamp' lfromtstamp "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'to timestamp' ltotstamp "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ). MESSAGE s015(swu_notif) " Selection Setting: &1 = &2 WITH 'current time' sy-uzeit "#EC NOTEXT INTO lmsgtext. lolog->addmessage( ).

prepare substitution stuff *

determine substitution profile which means no restriction PERFORM re77s0 IN PROGRAM mstt77s0 USING 'WORKF' 'DEFCL' lnoclass lsubrc. "#EC NOTEXT read the correlation between profile and tclass SELECT * FROM t77ro INTO TABLE lt77ro. "#EC CIGENBUFF replace NO_CLASS by space CLEAR wa_77ro-tclass.

MODIFY lt77ro FROM wa77ro TRANSPORTING tclass WHERE tclass = l_noclass. " class

call user exit which may change environment data

IF NOT rtexitprep[] IS INITIAL. LOOP AT rtexitprep. IF NOT rtexitprep-low IS INITIAL. CALL FUNCTION rtexitprep-low. ENDIF. " IF NOT rtexitprep-low IS INITIAL ENDLOOP. " LOOP AT rtexitprep ENDIF. " IF NOT rtexitprep[] IS INITIAL

Notification text Set

PERFORM GETDOCUMENT USING CDOCU_IDDIALOGTEXT P_PROL LLANGUDOC CHANGING LTEXTPROLOG. "PSEUDO CODE PERFORM GETDOCUMENT USING CDOCU_IDDIALOGTEXT P_EPIL LLANGUDOC CHANGING LTEXTEPILOG. "PSEUDO CODE

READ THE PROXY TABLE *

TO CHECK IF THE PROXY TABLE CONTAIN A MATCHING ENTRY THE EMAIL NEEDS TO BE SENT TO THE PROXY ADDRESS RATHER THAN TO THE END USER'S EMAIL IN CASE IF "YES SELECT PROXYADDR INTO LPROXY_EMAIL FROM SWUTYP2ADR " SAP FORMS: MAP FORM TYPE TO PROXY MAIL ADDRESS WHERE FORM_TYPE = SPACE. ENDSELECT.

WORK ITEMS SELECTION *

PERFORM SELECT_WORKITEMS.

IF P_NEW IS INITIAL. PERFORM SELECTMODIFIEDWORKITEMS. ENDIF. " IF P_NEW IS INITIAL

NOTIFICATIONS FOR THESE WORK ITEMS SENDING *

PERFORM SENDWIMAILS. *WRITE NUMBER OF SENT MAILS TO THE LOG MESSAGE S022(SWU_NOTIF) " & WORK ITEMS SENT WITH LMAILSSENT "#EC NOTEXT INTO LMSGTEXT. LOLOG->ADDMESSAGE( ).

UPDATE THE SCHEDULING INFORMATION *

*AR UPDATE TABLE SWU_WLSCAN ONLY WHEN THE DEFAULT IS USED. IF LSETLASTRUN = 'X'. SWUWLSCAN-CURRNUMB = P_JOBSUF. SWUWLSCAN-LASTTS = LTOTSTAMP CLEAR SWUWLSCAN-LASTDATE. CLEAR SWUWLSCAN-LASTTIME. MODIFY SWU_WLSCAN. ENDIF. " IF LSETLASTRUN = 'X' *- SAVE THE TRACE LOLOG->SAVELOG( ). LOLOG->REFRESHLOG( ).

END OF THE REPORT *

FORM ROUTINES *

--------------------------------------------------------------------- * FORM SENDWIMAILS * --------------------------------------------------------------------- * SEND NOTIFICATIONS FOR THE WORK ITEMS IN TABLE LTWIID * --------------------------------------------------------------------- * FORM SENDWIMAILS.

DATA: L_SUBRC LIKE SY-SUBRC. " ABAP SYSTEM FIELD: RETURN CODE OF ABAP STATEMENTS DATA: WIRECIPIENTS TYPE TUSER_DATA OCCURS 0 WITH HEADER LINE. DATA: LSADDRESS TYPE TUSER_DATA. DATA: LUSERFOUND TYPE XFELD. " CHECKBOX FIELD-SYMBOLS: TYPE TUSERDATA.

READ THE SELECTED AGENTS (USERS) *

LOOP THRU ALL WORKITEMS. LOOP AT LTWIDATA. CLEAR LTUSERS. REFRESH LTUSERS. CLEAR WI_RECIPIENTS. WRITE TO LOG IF NOT XALWTR IS INITIAL. MESSAGE S014(SWUNOTIF) WITH LTWIDATA-WIID " WORK ITEM &1 BEING EDITED INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). ENDIF. " IF NOT XALWTR IS INITIAL DETERMINE THE RECIPIENTS. EXCLUDED AGENTS ARE REMOVED FROM TABLE WIAGENTLIST BY FM CALL FUNCTION 'RHWIAGENTS_GET' EXPORTING ACTWIID = LT_WIDATA-WIID SEARCH_DATE = SY-DATUM ONLY_USER = 'X' TABLES ACTORGTASK = EXCLUDED_AGENTS = WIAGENTLIST = LT_USERS EXCEPTIONS NOACTIVEPLVAR = 1 NOAGENTFOUND = 2 GENERAL_TASK = 3 BACKGROUND_TASK = 4 OTHERS = 5.

L_SUBRC = SY-SUBRC. IN CONTRARY TO VERSION 1 WE DON'T SEND TO ALL USERS

DETERMINE THE RECIPIENTS OF THE MESSAGES TO BE SENT *

HANDLE GENERAL TASKS IF L_SUBRC = 3. MESSAGE S004(SWUNOTIF) WITH LTWIDATA-WIID " WORK ITEM &1 HAS NO SELECTED AGENT. SEND NOT POSSIBLE INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). CONTINUE. ENDIF. " IF L_SUBRC = 3 DO USERS EXIST? CHECK L_SUBRC = 0. CONSIDER SUBSTITUTION. MAYBE IT'S CLASS-SPECIFIC PERFORM ADD_SUBSTITUTES TABLES LT_USERS USING LTWIDATA CHANGING L_SUBRC. LOOP AT LT_USERS. LUNAME = LTUSERS-OBJID. CONSIDER USER RESTRICTION IF NOT PUSER IS INITIAL AND PUSER NE L_UNAME. NO, IT'S NOT THE USER IN THE SELECTION OPTION -> SKIP CONTINUE. ENDIF. " IF NOT PUSER IS INITIAL AND PUSER NE L_UNAME DID WE ALREADY SEND TO THE USER? CLEAR: WAUSERDATA, L_USERFOUND, LTABIX. READ TABLE LTUSERDATA WITH KEY UNAME = LT_USERS-OBJID BINARY SEARCH ASSIGNING . L_TABIX = SY-TABIX. " NOTE 739988 IF SY-SUBRC = 0. LUSERFOUND = 'X'.

ENDIF. " IF SY-SUBRC = 0 IF SENDING ONLY ONE MESSAGE FOR ALL WORK ITEMS... IF SOPT-ONE4ALL = 'X' AND LUSER_FOUND = 'X'. MESSAGE TO THIS USER HAS ALREADY BEEN SENT. CONTINUE. " GOTO LOOP START ENDIF. " IF SOPT-ONE4ALL = 'X' AND LUSER_FOUND = 'X' IF LUSERFOUND IS INITIAL. NEW USER WAUSERDATA-UNAME = L_UNAME. IF L_TABIX IF LWIHEADER-WI_TYPE = 'D' TAKE THE NORMAL WORK ITEM TEXT LWITYPE = 'W'. "#EC NOTEXT LTASK = LWI_HEADER-WIRHTASK. ENDIF. " IF LWIHEADER-WI_TYPE = 'D' DATA: LSYS TYPE SYSTSYSID. " ABAP SYSTEM FIELD: NAME OF SAP SYSTEM DATA:LWAMAILBODY TYPE SOLI, "MAIL BODY LWAMAILBODYl TYPE SOLI, "MAIL BODY LWASTREAM TYPE SWRTXTLIN, " WORKFLOW INTERFACES: TEXT LINE

L_URL TYPE ZZURL. " URL PERFORM VARIABLE SUBSTITUTION FOR TASK DESCRIPTION. try. call function 'swugettask_textlines' EXPORTING TASK = L_TASK USAGE = LWITYPE LANGUAGE = LWIHEADER-WI_LANG LANGUAGE = LMAILLANGUAGE WIHEADER = LWIHEADER TABLES STREAMTEXTLINES = LTSTREAMLINES EXCEPTIONS WRONG_USAGE = 01 TEXTNOTFOUND = 02 TEXTSYSTEMERROR = 03. LOOP AT LTSTREAMLINES INTO LWA_STREAM. SPLIT LWASTREAM-TEXTLINE AT CLABAP_CHARUTILITIES=>CRLF INTO TABLE LIMAILBODY_TEMP. APPEND LINES OF LIMAILBODY_TEMP TO LIMAILBODY. ENDLOOP. " LOOP AT LTSTREAMLINES INTO LWA_STREAM APPEND LWAMAILBODY TO LIMAILBODY. LSUBJECT = LWIHEADER-WITEXT. SELECT SINGLE URL " URL FROM ZAT_LINK " TABLE FOR PORTAL LINK INTO L_URL WHERE TASKID = L_TASK. IF SY-SUBRC IS NOT INITIAL. SELECT SINGLE URL " URL FROM ZAT_LINK " TABLE FOR PORTAL LINK INTO L_URL WHERE TASKID = 'TS00000000'. ENDIF. " IF SY-SUBRC IS NOT INITIAL CLEAR LWAMAILBODY.

APPEND LWAMAILBODY TO LIMAILBODY. CONCATENATE:' ' 'PLEASE CLICK THE BELOW LINK AND TAKE APPROPRIATE ACTION.' ' ' INTO LWAMAILBODY. APPEND LWAMAILBODY TO LIMAILBODY. CLEAR LWAMAILBODY. CONCATENATE 'FIORI PORTAL LINK:' 'CRLF INTO TABLE LIMAILBODY_TEMP. APPEND LINES OF LIMAILBODY_TEMP TO LIMAILBODY. ENDLOOP " LOOP AT LTSTREAMLINES INTO LWA_STREAM APPEND LWAMAILBODY TO LIMAILBODY. LSUBJECT = LWIHEADER-WITEXT. SELECT SINGLE URL " URL FROM ZAT_LINK " TABLE FOR PORTAL LINK INTO L_URL WHERE TASKID = L_TASK. IF SY-SUBRC IS NOT INITIAL. SELECT SINGLE URL " URL FROM ZAT_LINK " TABLE FOR PORTAL LINK INTO L_URL WHERE TASKID = 'TS00000000'. ENDIF. " IF SY-SUBRC IS NOT INITIAL CLEAR LWAMAILBODY. APPEND LWAMAILBODY TO LIMAILBODY. CONCATENATE:' ' 'PLEASE CLICK THE

BELOW LINK AND TAKE APPROPRIATE ACTION.' ' ' INTO LWAMAILBODY. APPEND LWAMAILBODY TO LIMAILBODY. CLEAR LWAMAILBODY. CONCATENATE 'FIORI PORTAL LINK:' '' 'CLICK HERE' '' INTO LWAMAILBODY. APPEND LWAMAILBODY TO LIMAILBODY. CLEAR LWAMAILBODY. APPEND LWAMAILBODY TO LIMAILBODY. CLEAR LWAMAILBODY . LIMAILBODY_TM[] = LIMAILBODY[]. CLEAR LIMAILBODY[]. LOOP AT LIMAILBODY_TM INTO LWAMAILBODY. CONCATENATE ' ' ' ' '' LWAMAILBODY-LINE '' ' ' ' ' '' INTO LWAMAILBODY1-LINE RESPECTING BLANKS. APPEND LWAMAILBODY1 TO LIMAILBODY. CLEAR: LWAMAILBODY,LWAMAILBODY1. ENDLOOP. " LOOP AT LIMAILBODY_TM INTO LWAMAILBODY CONVERT TABLE TO STRING FOR EASIER HANDLING PERFORM TLINETOSTRING TABLES LT_TEXTLINES[] CHANGING LBODY. ENDTRY. IF L_BODY IS INITIAL. IF THERE IS NO TEXT, WE CREATE A DEFAULT TEXT.

L_BODY = 'THIS WORK ITEM HAS NO DESCRIPTION.'(M06). ENDIF. " IF L_BODY IS INITIAL ASSEMBLE MAIL BODY: PROLOG ... WI TEXT ... EPILOG CONCATENATE LTEXTPROLOG L_BODY LTEXTEPILOG INTO L_BODY. SET SUBJECT AND LANGUAGE OF THE MAIL MESSAGE. IF PSNAC IS INITIAL OR PSNAN IS INITIAL. LMAILSUBJECT = L_WIHEADER-WITEXT. ELSE. " ELSE -> IF PSNAC IS INITIAL OR PSNAN IS INITIAL PERFORM GETMESSAGETEXT USING PSNAC PSNAN LMAILLANGUAGE SY-SYSID LWIHEADER-WI_TEXT CHANGING LMAILSUBJECT. ENDIF. " IF PSNAC IS INITIAL OR PSNAN IS INITIAL ELSE. " ELSE -> IF S_OPT-ONE4ALL IS INITIAL THERE IS ONLY ONE MESSAGE FOR ALL WORK ITEMS. SET LANGUAGE OF THE MAIL MESSAGE. IF P_LANGU IS INITIAL. LMAILLANGUAGE = SY-LANGU. ELSE. " ELSE -> IF P_LANGU IS INITIAL LMAILLANGUAGE = P_LANGU. ENDIF. " IF P_LANGU IS INITIAL SUBJECT... IF PSNAC IS INITIAL OR PSNAN IS INITIAL. LMAILSUBJECT = '&: YOU HAVE RECEIVED NEW WORK ITEMS.'(S02). REPLACE '&' WITH SY-SYSID INTO LMAILSUBJECT. CONDENSE LMAILSUBJECT. ELSE. " ELSE -> IF PSNAC IS INITIAL OR PSNAN IS INITIAL PERFORM GETMESSAGETEXT USING PSNAC PSNAN LMAILLANGUAGE SY-SYSID '' CHANGING LMAILSUBJECT.

ENDIF. " IF PSNAC IS INITIAL OR PSNAN IS INITIAL BODY... LBODY = LTEXT_PROLOG. ENDIF. " IF S_OPT-ONE4ALL IS INITIAL

CREATE THE TEXT BODY PART *

FILL THE DOCUMENT LT_CONTENT WITH THE TEXT BUILT SO FAR, E.G. WORKITEM LONG TEXT. PERFORM STRINGTOTABLE USING L_BODY CHANGING LTCONTENTTXT[]. DESCRIBE TABLE LTCONTENTTXT LINES L_COUNT. UPDATE THE PACKING LIST. CLEAR LTPACKINGLIST_TXT. LTPACKINGLISTTXT-HEADSTART = 1. LTPACKINGLISTTXT-HEADNUM = 0. LTPACKINGLISTTXT-BODYSTART = 1. LTPACKINGLIST_TXT-BODYNUM = LCOUNT. LTPACKINGLISTTXT-DOCTYPE = 'TXT'. LTPACKINGLISTTXT-OBJNAME = 'MESSAGE'(003). LTPACKINGLISTTXT-OBJDESCR = LMAILSUBJECT. LTPACKINGLISTTXT-OBJLANGU = LMAILLANGUAGE. APPEND LTPACKINGLIST_TXT. UPDATE THE CURRENT LINE NUMBER. LLINENO = L_COUNT. FILL THE DOCUMENT DATA. READ TABLE LTCONTENTTXT INDEX L_COUNT. LTDOCUMENTDATA-DOC_SIZE = ( LCOUNT - l ) * 255 + STRLEN( LTCONTENT_TXT ). LTDOCUMENTDATA-OBJ_NAME = 'SAPOFFICE'(002). LTDOCUMENTDATA-OBJ_DESCR = LMAILSUBJECT. IF LWIHEADER IS INITIAL. LWIHEADER-WI_PRIO = 5. ENDIF. " IF LWIHEADER IS INITIAL LTDOCUMENTDATA-OBJPRIO = LWIHEADER-WIPRIO. LTDOCUMENTDATA-PRIORITY = L_WIHEADER-WIPRIO.

SET L_EXPRESS FLAG. *

IF LWIHEADER-WI_PRIO = l. L_EXPRESS = 'X'. ENDIF. " IF LWIHEADER-WI_PRIO = l NOTE: IN THE CASE WHEN ONLY ONE MESSAGE IS SENT FOR THE WHOLE WORKLIST, WE DO NOT CALCULATE WHETHER ANY HIGH-PRIORITY WORK ITEMS ARE AMONG THEN.

CREATE THE MESSAGE TO BE SENT. *

APPEND LINES OF LTCONTENTTXT TO LT_CONTENT. APPEND LINES OF LTPACKINGLIST_TXT TO LTPACKINGLIST.

SEND THE MESSAGE *

IF SOPT-NOSHORTCUTS = 'X'. NO SHORTCUT ATTACHMENT INVOLVED -> SEND ONE MESSAGE TO SEVERAL RECIPIENTS AT ONCE. TRANSFORM RECIPIENT LIST LTREALRECIPIENTS-REC_TYPE = CESCUNIX. LOOP AT PT_RECIPIENTS. LTREALRECIPIENTS-RECEIVER = PT_RECIPIENTS-EMAIL. NOTE 808971 IF NOT RTEXITADDR[] IS INITIAL. PERFORM CONVERT_HEADER USING LWIHEADER CHANGING LSWIHDR. LMAILADDRESS = PT_RECIPIENTS-EMAIL. LOOP AT RTEXITADDR. IF NOT RTEXITADDR-LOW IS INITIAL. CALL FUNCTION RTEXITADDR-LOW EXPORTING IUNAME = PTRECIPIENTS-UNAME IWIHDR = LSWIHDR CHANGING CEMAIL = LMAIL_ADDRESS. LTREALRECIPIENTS-RECEIVER = LMAILADDRESS.

ENDIF. " IF NOT RTEXITADDR-LOW IS INITIAL ENDLOOP. " LOOP AT RTEXITADDR ENDIF. " IF NOT RTEXITADDR[] IS INITIAL IF NOT LTREALRECIPIENTS-RECEIVER IS INITIAL. APPEND LTREALRECIPIENTS. ENDIF. " IF NOT LTREALRECIPIENTS-RECEIVER IS INITIAL ENDLOOP. " LOOP AT PT_RECIPIENTS IF NOT LTREALRECIPIENTS[] IS INITIAL. NOW SEND PERFORM SO_SEND TABLES LT_CONTENT LTOBJECTHEADER LTPACKINGLIST LTREALRECIPIENTS USING PWIID LTDOCUMENTDATA L_SUBJECT LIMAILBODY L_EXPRESS CHANGING LSENTTO_ALL. ENDIF. " IF NOT LTREALRECIPIENTS[] IS INITIAL ELSE. " ELSE -> IF SOPT-NOSHORTCUTS = 'X' SHORTCUTS INVOLVED -> SEND TO EACH RECIPIENT INDIVIDUALLY. THE ATTACHMENT CONTAINS THE (ONE) RECIPIENT'S INTERNET MAIL ADDRESS. WE SEND DIRECTLY TO THE INTERNET MAIL ADDRESS. PERFORM SEND_INDIVIDUAL TABLES LT_CONTENT LTOBJECTHEADER LTPACKINGLIST PT_RECIPIENTS USING LTDOCUMENTDATA L_EXPRESS LLINENO LWIHEADER L_SUBJECT

LIMAILBODY CHANGING LSENTTO_ALL. ENDIF. " IF SOPT-NOSHORTCUTS = 'X' REFRESH PT_RECIPIENTS. ENDFORM. " SEND_MESSAGES --------------------------------------------------------------------- * FORM SEND_INDIVIDUAL * --------------------------------------------------------------------- * SEND TO AN INDIVIDUAL USER * --------------------------------------------------------------------- * FORM SENDINDIVIDUAL TABLES PTCONTENT STRUCTURE SOLISTI1 PTOBJECTHEADER STRUCTURE SOLISTI1 PTPACKINGLIST STRUCTURE SOPCKLSTI1 PTRECIPIENTS TYPE TUSERDATATAB USING PDOCUMENTDATA LIKE SODOCCHGI1 " DATA OF AN OBJECT WHICH CAN BE CHANGED PEXPRESS LIKE SOS04-LSEX " SEND EXPRESS PLINENO TYPE I " LINE_NO OF TYPE INTEGERS PWIHEADER LIKE SWWWIHEAD " WORKFLOW RUNTIME: HEADER TABLE FOR ALL WORK ITEM TYPES PSUBJECT TYPE SWWWITEXT " SHORT DESCRIPTION OF CONTENTS PBODY TYPE BCSYTEXT CHANGING PSENTTO_ALL LIKE SY-BINPT. " ABAP SYSTEM FIELD: BATCH INPUT PROCESSING ACTIVE DATA: L_FAILED, L_SUCCESS, LTREALRECIPIENTS LIKE SOMLRECI1 occurs 0 with header line, " SAPOFFICE: STRUCTURE OF THE API RECIPIENT LIST LT_CONTENT LIKE SOLISTI1 OCCURS 0, " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 LTOBJECTHEADER LIKE SOLISTI1 OCCURS 0, " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 LTPACKINGLIST TYPE SOPCKLSTI1_TAB, LLINENO TYPE I, " LINE_NO OF TYPE INTEGERS LSWIHDR TYPE SWR_WIHDR. " WORK ITEM STRUCTURE

LOOP AT PT_RECIPIENTS. LLINENO = PLINENO. REFRESH: LTREALRECIPIENTS. *- INITIALIZE WITH THE VALUES PASSED IN LTCONTENT[] = PTCONTENT[]. LTOBJECTHEADER[] = PTOBJECTHEADER[]. LTPACKINGLIST[] = PTPACKINGLIST[]. *- ADD SAP SHORTCUT ATTACHMENTS IF XSCINB = 'X'. *- SHORTCUT LAUNCHING THE INBOX PERFORM ADDSHORTCUTINBOX USING PT_RECIPIENTS-UNAME PTRECIPIENTS-LOGONLANGU " NOTE: 84925l PTRECIPIENTS-EMAIL PWI_HEADER CHANGING LLINENO LT_CONTENT[] LTOBJECTHEADER[] LTPACKINGLIST[]. ENDIF. " IF XSCINB = 'X' IF XSCDIS = 'X'. *- SHORTCUT LAUNCHING THE INBOX PERFORM ADDSHORTCUTACTION USING PT_RECIPIENTS-UNAME PTRECIPIENTS-LOGONLANGU " NOTE: 84925l PT_RECIPIENTS-EMAIL PWIHEADER CACTIONDISPLAY CHANGING LLINENO LT_CONTENT[] LTOBJECTHEADER[] LTPACKINGLIST.

ENDIF. " IF XSCDIS = 'X' IF XSCEXE = 'X'. *- SHORTCUT LAUNCHING THE INBOX PERFORM ADDSHORTCUTACTION USING PT_RECIPIENTS-UNAME PTRECIPIENTS-LOGONLANGU " NOTE: 849251 PT_RECIPIENTS-EMAIL PWIHEADER CACTIONEXECUTE CHANGING LLINENO LT_CONTENT[] LTOBJECTHEADER[] LTPACKINGLIST[]. ENDIF. " IF XSCEXE = 'X' *- LET THE USER EXIT MODIFY THE ADDRESS IF NOT RTEXITADDR[] IS INITIAL. PERFORM CONVERT_HEADER USING PWIHEADER CHANGING LSWIHDR. LOOP AT RTEXITADDR. IF NOT RTEXITADDR-LOW IS INITIAL. CALL FUNCTION RTEXITADDR-LOW EXPORTING IUNAME = PTRECIPIENTS-UNAME IWIHDR = LSWIHDR CHANGING CEMAIL = PTRECIPIENTS-EMAIL. ENDIF. " IF NOT RTEXITADDR-LOW IS INITIAL ENDLOOP. " LOOP AT RTEXITADDR ENDIF. " IF NOT RTEXITADDR[] IS INITIAL IF PT_RECIPIENTS-EMAIL IS INITIAL. CONTINUE. ENDIF. " IF PT_RECIPIENTS-EMAIL IS INITIAL

*- COMPUTE THE SAPOFFICE RECIPIENT IF LPROXYEMAIL IS INITIAL. *- USE THE CURRENT RECIPIENT CLEAR LTREALRECIPIENTS. LTREALRECIPIENTS-RECEIVER = PT_RECIPIENTS-EMAIL. LTREALRECIPIENTS-REC_TYPE = CESCUNIX. APPEND LTREALRECIPIENTS. ELSE. " ELSE -> IF LPROXYEMAIL IS INITIAL SEND VIA PROXY THIS CURRENTLY ONLY WORKS VIA INTERNET MAIL LTREALRECIPIENTS-RECEIVER = LPROXYEMAIL. LTREALRECIPIENTS-REC_TYPE = CESCUNIX. APPEND LTREALRECIPIENTS. ENDIF. " IF LPROXYEMAIL IS INITIAL PERFORM SO_SEND TABLES LT_CONTENT LTOBJECTHEADER LTPACKINGLIST LTREALRECIPIENTS USING PWIHEADER-WI_ID PDOCUMENTDATA P_SUBJECT P_BODY P_EXPRESS CHANGING L_SUCCESS. IF L_SUCCESS IS INITIAL. L_FAILED = 'X'. ENDIF. " IF L_SUCCESS IS INITIAL ENDLOOP. " LOOP AT PT_RECIPIENTS IF L_FAILED IS INITIAL. PSENTTO_ALL = 'X'. ENDIF. " IF L_FAILED IS INITIAL ENDFORM. "SEND_INDIVIDUAL

--------------------------------------------------------------------- * FORM SO_SEND * --------------------------------------------------------------------- * SEND SAPOFFICE MESSAGE * --------------------------------------------------------------------- * FORM SOSEND TABLES PTCONTENT STRUCTURE SOLISTI1 PTOBJECTHEADER STRUCTURE SOLISTI1 PTPACKINGLIST STRUCTURE SOPCKLSTI1 PTREALRECIPIENTS STRUCTURE SOMLRECI1 USING PWIID LIKE SWWWIHEAD-WI_ID " WORK ITEM ID PDOCUMENTDATA LIKE SODOCCHGI1 " DATA OF AN OBJECT WHICH CAN BE CHANGED PSUBJECT TYPE SWWWITEXT " SHORT DESCRIPTION OF CONTENTS PBODY TYPE BCSYTEXT PEXPRESS LIKE SOS04-LSEX " SEND EXPRESS CHANGING PSENTTO_ALL LIKE SY-BINPT. " ABAP SYSTEM FIELD: BATCH INPUT PROCESSING ACTIVE DATA: LNEWOBJECT_ID LIKE SOFOLENTI1-OBJECTID. " SAPOFFICE: ID OF A SAPOFFICE OBJECT CLEAR LNEWOBJECT_ID. LITEMSSENT = 'X'. SEND BACK A DELIVERY AND A NON-DELIVERY REPORT. LOOP AT PTREALRECIPIENTS. NOTE l007893: DO NOT SEND ACKNOWLEDGMENT OF RECEIPT PTREALRECIPIENTS-NOTIF_DEL = 'X'. PTREALRECIPIENTS-NOTIF_NDEL = 'X'. IF NOT S_OPT-ONE4ALL IS INITIAL. PTREALRECIPIENTS-BLIND_COPY = 'X'. ENDIF. " IF NOT S_OPT-ONE4ALL IS INITIAL PTREALRECIPIENTS-EXPRESS = P_EXPRESS. MODIFY PTREALRECIPIENTS. ENDLOOP " LOOP AT PTREALRECIPIENTS DATA:LWA_RECI TYPE SOMLRECIl, " SAPOFFICE: STRUCTURE OF THE API RECIPIENT LIST LEMAILSUBJ TYPE STRING,

LSHORTSUB TYPE SOOBJDES, "SUBJECT LIRECEPIENT TYPE ZUTEMAILRECIPIENTTT, "EMAIL RECIPIENT LIST TABLE TYPE LWARECEPIENT TYPE ZUTEMAIL_RECIPIENT. " EMAIL RECIPIENT LIST STRUCTURE CONSTANTS : LCDOCTYPE_HTM TYPE SOOBJTP VALUE 'HTM', " CODE FOR DOCUMENT CLASS LCRECPTARGET TYPE ZRECIPIENT_TARGET VALUE 'TO', " RECIPIENT TARGET LCRECPTYPE TYPE ZRECIPIENT_TYPE VALUE 'E'. LOOP AT PTREALRECIPIENTS INTO LWA_RECI. CLEAR : LWA_RECEPIENT. LWARECEPIENT-RECIPIENTTYPE = LCRECPTYPE. LWARECEPIENT-RECIPIENTTARGET = LCRECPTARGET. LWARECEPIENT-RECIPIENT = LWARECI-RECEIVER. APPEND LWARECEPIENT TO LIRECEPIENT. CLEAR LWA_RECEPIENT. ENDLOOP " LOOP AT PTREALRECIPIENTS INTO LWA_RECI LEMAILSUBJ = P_SUBJECT. LSHORTSUB = P_SUBJECT. *--->CALL THIS FM TO SENE THE E-MAIL... CALL FUNCTION 'ZATSENDEMAILWF' EXPORTING IMFORMAT = LCDOCTYPEHTM IMSUBJECTSHORT = LSHORTSUB IMSUBJECTLONG = LEMAILSUBJ TABLES TRECEPIENTLIST = LI_RECEPIENT TMAILBODY = P_BODY EXCEPTIONS NO_TCODE = 1 NO_OKCODE = 2 NO_NAME = 3 OTHERS = 4.

IF SY-SUBRC IS INITIAL. COMMIT WORK. ENDIF. " IF SY-SUBRC IS INITIAL *********************CHANGE BY SUDIPTA CALL FUNCTION 'SONEWDOCUMENT_ATTSENDAPI1' EXPORTING DOCUMENTDATA = PDOCUMENT_DATA ** PUTINOUTBOX = ' ' IMPORTING SENTTOALL = P_SENTTOALL NEWOBJECTID = L_NEWOBJECTID TABLES PACKINGLIST = PTPACKING_LIST OBJECTHEADER = PTOBJECT_HEADER CONTENTSTXT = PTCONTENT RECEIVERS = PTREALRECIPIENTS EXCEPTIONS TOOMANYRECEIVERS = 1 DOCUMENTNOTSENT = 2 DOCUMENTTYPENOT_EXIST = 3 OPERATIONNOAUTHORIZATION = 4 PARAMETER_ERROR = 5 X_ERROR = 6 ENQUEUE_ERROR = 7 OTHERS = 8. * COMMIT WORK. *********************CHANGE BY SUDIPTA ........ WRITE TRACE. IF NOT XALWTR IS INITIAL. MESSAGE S003(SWUNOTIF) WITH LNEWOBJECTID " SAPOFFICE DOCUMENT &1 SENT INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). LIST THE ADDRESSESS.

LOOP AT PTREALRECIPIENTS WHERE NOT PROXY_ID IS INITIAL. PERFORM WRITESENDADDRESSEE USING PWIID PTREALRECIPIENTS. ENDLOOP. " LOOP AT PTREALRECIPIENTS WHERE NOT PROXY_ID IS INITIAL ENDIF. " IF NOT XALWTR IS INITIAL IF NOT PSENTTO_ALL IS INITIAL. PERFORM WRITESENDSUCCESS_ALL USING PWIID . ADD 1 TO LMAILSSENT. ELSE. " ELSE -> IF NOT PSENTTO_ALL IS INITIAL PERFORM WRITESENDFAILED_ALL USING PWIID . ENDIF. " IF NOT PSENTTO_ALL IS INITIAL DELETE THE ORIGINAL ENTRIES. THE ERROR CODE IS MISLEADING. DELETE PTREALRECIPIENTS WHERE NOT PROXY_ID IS INITIAL. IF NOT XALWTR IS INITIAL. LOOP AT PTREALRECIPIENTS WHERE RETRN_CODE = 0. PERFORM WRITESENDSUCCESS USING PWIID PTREALRECIPIENTS. ENDLOOP. " LOOP AT PTREALRECIPIENTS WHERE RETRN_CODE = 0 ENDIF. " IF NOT XALWTR IS INITIAL LOOP AT PTREALRECIPIENTS WHERE RETRN_CODE 0. PERFORM WRITESENDFAILED USING PWIID PTREALRECIPIENTS. ENDLOOP. " LOOP AT PTREALRECIPIENTS WHERE RETRN_CODE 0 ENDFORM. "SO_SEND --------------------------------------------------------------------- * FORM WRITESENDFAILED * --------------------------------------------------------------------- * * --------------------------------------------------------------------- * FORM WRITESENDFAILED USING VALUE(WIID) LIKE SWWWIHEAD-WIID " WORK ITEM ID

LTREALRECIPIENTS STRUCTURE SOMLRECI1. DATA: READABLE_RECIPIENTS LIKE SOUDNAMEI1 " SAPOFFICE: SAP NAME AND SAPOFFICE NAME OF A USER OCCURS 0 WITH HEADER LINE, TEXT_BUF(200). CLEAR READABLE_RECIPIENTS. READABLERECIPIENTS-USERID = LTREALRECIPIENTS-RECID. CALL FUNCTION 'SONAMECONVERT_API1' EXPORTING NAME = READABLE_RECIPIENTS TABLES NAMES = READABLE_RECIPIENTS EXCEPTIONS USERNOTEXIST = 1 PARAMETERERROR = 2 XERROR = 3 OTHERS = 4. REPORT ERROR MESSAGE S005(SWU_NOTIF) " ERROR WHEN SENDING WORK ITEM &1 WITH WIID READABLERECIPIENTS-FULLNAME INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). CASE LTREALRECIPIENTS-RETRN_CODE. WHEN 0. " SUCCESSFUL MESSAGE S373(WZ) WITH WI_ID " MESSAGE FOR WORK ITEM &1 SENT TO ADDRESS &2 INTO LMSGTEXT. WHEN 34. MESSAGE E376(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: USER DOES NOT EXIST INTO LMSGTEXT. WHEN 69. MESSAGE E374(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: SENDER NOT COMPLETED INTO LMSGTEXT.

WHEN 75. MESSAGE E375(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: ERROR MAILING INTO LMSGTEXT. WHEN 80. MESSAGE E377(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: ADDRESS DOES NOT EXIST INTO LMSGTEXT. WHEN 89. MESSAGE E378(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: ERROR IN CONFIGURATION FILE INTO LMSGTEXT. WHEN 90. MESSAGE E379(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: SENDMAIL TOKEN NOT FOUND INTO LMSGTEXT. WHEN 91. MESSAGE E380(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: PIPE COULD NOT BE OPENED INTO LMSGTEXT. WHEN 92. MESSAGE E381(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: PIPE COULD NOT BE CLOSED INTO LMSGTEXT. WHEN OTHERS. MESSAGE E371(WZ) WITH WI_ID " SENDING FAILED FOR WORK ITEM &1: SEND OPERATION FAILED INTO LMSGTEXT. ENDCASE. LOLOG->ADDMESSAGE( ). WRITE: / LMSGTEXT. ENDFORM. "WRITESENDFAILED --------------------------------------------------------------------- * FORM WRITESENDADDRESSEE * --------------------------------------------------------------------- *

FORM WRITESENDADDRESSEE USING VALUE(WIID) LIKE SWWWIHEAD-WI ID " WORK ITEM ID LTREALRECIPIENTS STRUCTURE SOMLRECI1. IF NOT XALWTR IS INITIAL. MESSAGE S011(SWUNOTIF) WITH WIID LTREALRECIPIENTS-RECEIVER " WORK ITEM &1 SENT TO &2 INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). WRITE: / LMSGTEXT. ENDIF. " IF NOT XALWTR IS INITIAL ENDFORM. "WRITESENDADDRESSEE --------------------------------------------------------------------- * FORM WRITESENDSUCCESS * --------------------------------------------------------------------- * FORM WRITESENDSUCCESS USING VALUE(WIID) LIKE SWWWIHEAD-WIID " WORK ITEM ID LTREALRECIPIENTS STRUCTURE SOMLRECIl. DATA: READABLE_RECIPIENTS LIKE SOUDNAMEIl " SAPOFFICE: SAP NAME AND SAPOFFICE NAME OF A USER OCCURS 0 WITH HEADER LINE. CLEAR READABLE_RECIPIENTS. READABLERECIPIENTS-USERID = LTREALRECIPIENTS-RECID. CALL FUNCTION 'SONAMECONVERT_APIl' EXPORTING NAME = READABLE_RECIPIENTS TABLES NAMES = READABLE_RECIPIENTS EXCEPTIONS USERNOTEXIST = l PARAMETER_ERROR = 2 X_ERROR = 3 OTHERS = 4. IF NOT XALWTR IS INITIAL. IF WI_ID IS INITIAL.

MESSAGE S0l2(SWU_NOTIF) " WORK ITEMS SENT TO &l WITH READABLE_RECIPIENTS-FULLNAME INTO LMSGTEXT. ELSE. " ELSE -> IF WI_ID IS INITIAL MESSAGE S0ll(SWU_NOTIF) " WORK ITEM &l SENT TO &2 WITH WIID READABLERECIPIENTS-FULLNAME INTO LMSGTEXT. ENDIF. " IF WI_ID IS INITIAL LOLOG->ADDMESSAGE( ). WRITE: / LMSGTEXT. ENDIF. " IF NOT XALWTR IS INITIAL ENDFORM. "WRITESENDSUCCESS &--------------------------------------------------------------------*& FORM WRITEERRORMSG &--------------------------------------------------------------------FORM WRITEERRORMSG USING P_WIID LIKE SWWWIHEAD-WIID " WORK ITEM ID P_MSGNO LIKE T100-MSGNR " MESSAGE NUMBER P_MSGV1 LIKE BALM-MSGV1 " MESSAGE VARIABLE P_RECIPIENT . WRITE THAT SOME ERROR HAS OCCURED. IF NOT PWIID IS INITIAL AND X_14ALL IS INITIAL. IF NOT PWIID IS INITIAL. SKIP. MESSAGE S009(SWUNOTIF) WITH PWI_ID " WORK ITEM &: ATTEMPT TO SEND FAILED INTO LMSGTEXT. ELSE. " ELSE -> IF NOT PWIID IS INITIAL MESSAGE S010(SWUNOTIF) WITH PWI_ID " UNABLE TO SEND WORK ITEMS INTO LMSGTEXT. ENDIF. " IF NOT PWIID IS INITIAL WRITE: / LMSGTEXT. LOLOG->ADDMESSAGE( ). ENDIF. " IF NOT PWIID IS INITIAL AND IF NOT P_RECIPIENT IS INITIAL. WRITE: / 'ADDRESSEE:'(M09), 20 P_RECIPIENT.

ENDIF. " IF NOT P_RECIPIENT IS INITIAL WRITE THE CONCRETE REASON. MESSAGE ID PMSGNO TYPE 'E' NUMBER PMSGNO WITH P_MSGV1 INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). WRITE: / LMSGTEXT. WRITE: /. ENDFORM. " WRITEERRORMSG &--------------------------------------------------------------------*& FORM WRITESENDFAILED_ALL &--------------------------------------------------------------------FORM WRITESENDFAILEDALL USING PWIID LIKE SWWWIHEAD-WIID. " WORK ITEM ID IF NOT PWIID IS INITIAL. SKIP. MESSAGE S009(SWUNOTIF) WITH PWI_ID " WORK ITEM &: ATTEMPT TO SEND FAILED INTO LMSGTEXT. ELSE. " ELSE -> IF NOT PWIID IS INITIAL MESSAGE S010(SWUNOTIF) WITH PWI_ID " UNABLE TO SEND WORK ITEMS INTO LMSGTEXT. ENDIF. " IF NOT PWIID IS INITIAL WRITE: / LMSGTEXT. LOLOG->ADDMESSAGE( ). ENDFORM. " WRITESENDFAILED_ALL &--------------------------------------------------------------------*& FORM WRITESENDSUCCESS_ALL &--------------------------------------------------------------------FORM WRITESENDSUCCESSALL USING PWIID LIKE SWWWIHEAD-WIID. " WORK ITEM ID IF NOT XALWTR IS INITIAL. " TRACE IF NOT PWIID IS INITIAL. SKIP. MESSAGE S007(SWUNOTIF) WITH PWI_ID " WORK ITEM &: SEND OK

INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). ELSE. " ELSE -> IF NOT PWIID IS INITIAL MESSAGE S008(SWUNOTIF) WITH PWI_ID " WORK ITEMS SENT SUCCESSFULLY INTO LMSGTEXT. LOLOG->ADDMESSAGE( ). ENDIF. " IF NOT PWIID IS INITIAL ENDIF. " IF NOT XALWTR IS INITIAL ENDFORM. " WRITESENDSUCCESS_ALL &--------------------------------------------------------------------*& FORM WRITENOTHINGSENT &--------------------------------------------------------------------FORM WRITENOTHINGSENT. IF NOT XALWTR IS INITIAL. DESCRIBE TABLE LTWIDATA. MESSAGE S006(SWU_NOTIF) WITH SY-TFILL " & WORK ITEMS WERE READ. NONE WERE SENT INTO LMSGTEXT. WRITE: / LMSGTEXT. LOLOG->ADDMESSAGE( ). ENDIF. " IF NOT XALWTR IS INITIAL ENDFORM. " WRITENOTHINGSENT --------------------------------------------------------------------- * FORM SELECT_WORKITEMS * --------------------------------------------------------------------- * SELECT WORK ITEMS FROM THE DATABASE * --------------------------------------------------------------------- * FORM SELECT_WORKITEMS. SELECT THOSE WORKITEMS WITH THE CORRECT TASK, STATE AND CREATION DATE AND TIME.

THE SELECT STATEMENT ENCOURAGES ONE OF THE DATABASE INDICES * TO BE USED. EITHER THE TASK INDEX OR THE STATUS/TYPE INDEX. * TESTS SHOW THAT THIS REALLY DOES INFLUENCE THE DATABASE ACCESS * POSITIVELY. *

THIS ALGORITHM WILL BE INEFFICIENT WHEN TASKS ARE EXCLUDED RATHER * THAN INCLUDED. * THE COMBINATION 'WAITING' AND NOTIFICATION/DEADLINE TYPE * CANNOT OCCUR. * IF TASK_SEL[] IS INITIAL. "NO TASKS USE THE TYPE/STATUS INDEX. SELECT WI_ID TCLASS INTO CORRESPONDING FIELDS OF TABLE LTWIDATA FROM SWWWIHEAD " WORKFLOW RUNTIME: HEADER TABLE FOR ALL WORK ITEM TYPES WHERE WITYPE = WINORMAL AND WISTAT = WISTATUS_READY AND RETRY_CNT = '0' AND NOTE 969538: CREATMP > LFROM_TSTAMP AND CREATMP LFROM_TSTAMP AND CREATMP REMOVE READ TABLE LTEXCLAGENTS WITH KEY OBJID = LTADDUSERS-SUBSTITUTE TRANSPORTING NO FIELDS BINARY SEARCH. IF SY-SUBRC IS INITIAL. DELETE LTADDUSERS. ENDIF. " IF SY-SUBRC IS INITIAL IF LTADDUSERS-PROFILE IS INITIAL.

APPLIES TO ALL TCLASSES CONTINUE. ELSE. " ELSE -> IF LTADDUSERS-PROFILE IS INITIAL LTCLASS = PWI_DATA-TCLASS. " CLASS IF LTCLASS = LNOCLASS. " CLASS CLEAR L_TCLASS. ENDIF. " IF LTCLASS = LNOCLASS READ TABLE LT_77RO WITH KEY REPPR = LTADDUSERS-PROFILE TCLASS = L_TCLASS " CLASS TRANSPORTING NO FIELDS. IF SY-SUBRC NE 0. NO MATCH -> DELETE DELETE LTADDUSERS. ENDIF. " IF SY-SUBRC NE 0 ENDIF. " IF LTADDUSERS-PROFILE IS INITIAL ENDLOOP! " LOOP AT LTADDUSERS ENDLOOP " LOOP AT PT_USERS UPDATE THE USER TABLE LOOP AT LTADDUSERS. PTUSERS-OTYPE = CPDOTYPEUSR. PTUSERS-OBJID = LTADD_USERS-SUBSTITUTE. APPEND PT_USERS. ENDLOOP " LOOP AT LTADDUSERS SORT PT_USERS BY OTYPE OBJID. DELETE ADJACENT DUPLICATES FROM PT_USERS. ENDFORM. " ADD_SUBSTITUTES &--------------------------------------------------------------------*& FORM UPDATE_SUBSTITUTIONS &--------------------------------------------------------------------DETERMINE ALL SUBSTITUTES OF A GIVEN AGENT REGARDLESS OF THE PROFILE/TCLASS ---------------------------------------------------------------------- * FORM UPDATESUBSTITUTIONS TABLES PUSER_SUBST TYPE TSUBSTITUTION TAB

USING PUSERTAB STRUCTURE SWHACTOR CHANGING P_RC LIKE SY-SUBRC. " ABAP SYSTEM FIELD: RETURN CODE OF ABAP STATEMENTS DATA: LT_AGENTS LIKE SWHACTOR OCCURS 0 WITH HEADER LINE, " RULE RESOLUTION RESULT LTSUBST TYPE TSUBSTITUTION OCCURS 0 with HEADER LINE, SUBST_STR LIKE STRUC OCCURS 0 WITH HEADER LINE, " STRUCTURE INFORMATION FOR DATABASE PCH SUBST_SETTINGS LIKE PADD2. " ADDITIONAL DATA FOR RELATIONSHIPS: 2l0 SPECIFIED SUBSTITUTE DATA: LTINBOXVIEWPASS TYPE TABLE OF HRWFUSERV. " TRANSFER STRUCTURE TO FM ORGINFOAND_TASK DATA: LS_SUBSTITUTE TYPE SWRAGENT. " ROLE RESOLUTION RESULT DATA: L_TIMEZONE TYPE TIMEZONE. " TIME ZONE DATA: LCURRENTTIME TYPE TIMESTAMP. " UTC TIME STAMP IN SHORT FORM (YYYYMMDDHHMMSS) DATA: LACTBEGDA TYPE OBJEC-BEGDA. " START DATE DATA: LACTENDDA TYPE OBJEC-ENDDA. " END DATE CHECK FOR SUBSTITUTION *- NOTE 1492911: SUBSTITUTION AND TIME ZONES TIME ZONE OF AGENT CALL FUNCTION 'RHGETTIMEZONE' EXPORTING IVUSERNAME = PUSERTAB-OBJID IMPORTING EVTIMEZONE = LTIMEZONE. CURRENT TIME IN TIME ZONE OF AGENT GET TIME STAMP FIELD LCURRENTTIME. CONVERT TIME STAMP LCURRENTTIME TIME ZONE L_TIMEZONE INTO DATE LACTBEGDA. LACTENDDA = LACTBEGDA. CALL FUNCTION 'RHSUBSTITUTESGET' EXPORTING ACT_PLVAR = SPACE ACTOTYPE = PUSER_TAB-OTYPE

ACTOBJID = PUSER_TAB-OBJID ACTBEGDA = LACT_BEGDA ACTENDDA = LACT_ENDDA SHOWHOLDERFLAG = 'X' AUTHORITY_CHECK = 'X' TABLES SUBST_OBJ = SUBSTSTR = SUBSTSTR EXCEPTIONS NOSUBSTITUTEFOUND = 1 OTHERS = 2. IF SY-SUBRC NE 0. EXIT. " NO SUBSTITUTES ENDIF. " IF SY-SUBRC NE 0 LOOP AT SUBST_STR. SUBSTSETTINGS = SUBSTSTR-VADATA. CHECK IF SUBSTITUTE HAS ADOPTED THE SUBSTITUTION AT THE MOMENT IF ( NOT P_PSUBST IS INITIAL ) AND ( SUBST_SETTINGS-ACTIVE IS INITIAL ). LSSUBSTITUTE-OTYPE = SUBSTSTR-OTYPE. LSSUBSTITUTE-OBJID = SUBSTSTR-OBJID. CALL METHOD CLSWLSUBSTITUTION=>GETADOPTEDSUBSTITUTIONS EXPORTING ISUBSTITUTE = LSSUBSTITUTE IMPORTING ETINBOXVIEW = LT_INBOXVIEWPASS. READ TABLE LTINBOXVIEW_PASS WITH KEY OTYPE = PUSERTAB-OTYPE OBJID = PUSERTAB-OBJID TRANSPORTING NO FIELDS. IF SY-SUBRC 0. CONTINUE. ENDIF. " IF SY-SUBRC 0 ELSE. " ELSE -> IF ( NOT P_PSUBST IS INITIAL ) AND IF SUBST_SETTINGS-ACTIVE IS INITIAL.

CONTINUE. ENDIF. " IF SUBST_SETTINGS-ACTIVE IS INITIAL ENDIF. " IF ( NOT P_PSUBST IS INITIAL ) AND IF NOT SUBST_SETTINGS-ACTIVE IS INITIAL. IF SUBSTSTR-OTYPE = CPDOTYPEUSR. ADD THE ENTRY DIRECTLY LTSUBST-USER = PUSER_TAB-OBJID. LTSUBST-SUBSTITUTE = SUBSTSTR-OBJID. LTSUBST-PROFILE = SUBSTSETTINGS-REPPR. APPEND LT_SUBST. ELSE. " ELSE -> IF SUBSTSTR-OTYPE = CPDOTYPEUSR RESULT IS ORG UNIT -> COMPUTE ASSOCIATED USERS CALL FUNCTION 'RHSTRUCGET' EXPORTING ACTOTYPE = SUBSTSTR-OTYPE ACTOBJID = SUBSTSTR-OBJID ACTWEGID = 'SAPTAGT' TABLES RESULTTAB = LTAGENTS EXCEPTIONS NOPLVARFOUND = 1 NOENTRYFOUND = 2 OTHERS = 3. LOOP AT LT_AGENTS. IF LTAGENTS-OTYPE = CPDOTYPEUSR. ADD THE ENTRY DIRECTLY LTSUBST-USER = SUBSTSTR-OBJID. LTSUBST-SUBSTITUTE = LTAGENTS-OBJID. LTSUBST-PROFILE = SUBSTSETTINGS-REPPR. APPEND LT_SUBST. ENDIF. " IF LTAGENTS-OTYPE = CPDOTYPEUSR ENDLOOP. " LOOP AT LT_AGENTS ENDIF. " IF SUBSTSTR-OTYPE = CPDOTYPEUSR ENDIF. ENDLOOP. " LOOP AT SUBST_STR

APPEND NEW SUBSTITUTIONS TO GLOBAL SUBSTITUTIONS AND TO PARAMETER APPEND LINES OF LTSUBST TO GSUBSTITUTIONS. APPEND LINES OF LTSUBST TO PUSER_SUBST. ENDFORM. "UPDATE_SUBSTITUTIONS &--------------------------------------------------------------------*& FORM ADDSHORTCUTINBOX &--------------------------------------------------------------------ADD SHORTCUT ATTACHMENT LAUNCHING TX SO0l ---------------------------------------------------------------------- * FORM ADDSHORTCUTINBOX USING P_USER TYPE SYUNAME " USER NAME P_LANGU TYPE SYLANGU " LANGUAGE KEY P_EMAIL TYPE STRING PWIHEADER TYPE SWWWIHEAD " WORKFLOW RUNTIME: HEADER TABLE FOR ALL WORK ITEM TYPES CHANGING PLINENO TYPE I " LINE_NO OF TYPE INTEGERS PTCONTENT TYPE TSOLISTIl_TAB PTHEADER TYPE TSOLISTIl_TAB PTPACKING TYPE SOPCKLSTIlTAB. ADD THE ATTACHMENT TO THE DOCUMENT CONTENT. DATA: LT_ATTACH LIKE SOLISTIl OCCURS 0. " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 DATA: LT_CONTENT LIKE SOLISTIl OCCURS 0. " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 DATA: LT_HEADER LIKE SOLISTIl OCCURS 0 WITH HEADER LINE. " SAPOFFICE: SINGLE LIST "WITH COLUMN LENGTH 255 DATA: LT_PACKING LIKE SOPCKLSTIl OCCURS 0 WITH HEADER LINE. " SAPOFFICE: DESCRIPTION OF IMPORTED OBJECT COMPONENTS TAKE OVER EXISTING LINES LTHEADER[] = PTHEADER[]. LTCONTENT[] = PTCONTENT[]. LTPACKING[] = PTPACKING[]. *- ASSEMBLE SHORTCUT PERFORM CREATESHORTCUTINBOX USING PUSER PLANGU PEMAIL PLOGON CHANGING LT_ATTACH[].

DESCRIBE TABLE LTATTACH LINES LCOUNT. APPEND LINES OF LTATTACH TO LTCONTENT. *- ATTACHMENT HEADER CLEAR LTHEADER. REFRESH LTHEADER. LT_HEADER = 'GO TO INBOX'(005). "FILE NAME APPEND LT_HEADER. CLEAR LT_HEADER. LTHEADER = '&SOFORMAT=ASC'. " THIS INDICATES THAT IT IS ASCII. APPEND LT_HEADER. *- UPDATE THE PACKING LIST. CLEAR LT_PACKING. LTPACKING-HEADSTART = 1. LTPACKING-HEADNUM = 2. LTPACKING-BODYSTART = PLINENO + 1. LTPACKING-BODYNUM = L_COUNT. LTPACKING-DOCTYPE = 'SAP'. LTPACKING-DOCSIZE = 255 * L_COUNT. LTPACKING-OBJNAME = 'INBOX'. LTPACKING-OBJDESCR = 'GO TO INBOX'(005). LTPACKING-OBJLANGU = P_WIHEADER-WILANG. LTPACKING-OBJLANGU = P_LANGU. APPEND LT_PACKING. *- PASS PARAMETERS BACK ADD LCOUNT TO PLINE_NO. PTHEADER[] = LTHEADER[]. PTCONTENT[] = LTCONTENT[]. PTPACKING[] = LTPACKING[]. ENDFORM. " ADDSHORTCUTINBOX &-------------------------------------------------------------------*& FORM CREATESHORTCUTINBOX &-------------------------------------------------------------------CREATE SHORTCUT LAUNCHING TRANSACTION SO01 (SAPOFFICE INBOX) --------------------------------------------------------------------- *

FORM CREATESHORTCUTINBOX USING P_USER TYPE SYUNAME " USER NAME P_LANGU TYPE SYLANGU " LANGUAGE KEY P_EMAIL TYPE STRING PLOGONID TYPE TEXT50 " TEXT FIELD CHANGING PTATTACH TYPE SOLITAB. *- CREATE SAP SHORTCUT ATTACHMENT ENTERED( 'CREATEINBOXATTACHMENT' ). DATA: LLOGONID TYPE TEXT50. " TEXT FIELD DATA: L_SCRAP TYPE TEXT255. " TEXT, 255 CHARACTERS *- ASSEMBLE PIECE FOR EMAIL ADDRESS *- IS REQUIRED WHEN SENDING TO PROXY IF NOT P_EMAIL IS INITIAL. CONCATENATE '[WORKFLOW]' L_CRLF "#EC NOTEXT 'EMAIL=' P_EMAIL "#EC NOTEXT INTO L_SCRAP. "#EC NOTEXT ENDIF. " IF NOT P_EMAIL IS INITIAL *- PARAMETER CONVERSIONS LLOGONID = PLOGONID. *- CREATE THE SHORTCUT AS TABLE CALL FUNCTION 'SWNCREATESHORTCUT' EXPORTING I_TRANSACTION = 'SO01' "#EC NOTEXT I_REPORT = ISYSTEMCOMMAND = I_PARAMETER = ISAPLOGONID = LLOGONID I_SYSID = SY-SYSID I_GUIPARM = IUSER = PUSER ILANGUAGE = PLANGU I_WINDOWSIZE = 'NORMAL WINDOW' "#EC NOTEXT I_TITLE = ICUSTOM = LSCRAP

IMPORTING SHORTCUTTABLE = PTATTACH SHORTCUT_STRING = EXCEPTIONS INCONSISTENT_PARAMETERS = OTHERS = 1. IF SY-SUBRC 0. REFRESH PT_ATTACH. ENDIF. " IF SY-SUBRC 0 LEAVING( 'CREATEINBOXATTACHMENT' ). ENDFORM. "CREATESHORTCUTINBOX *&--------------------------------------------------------------------- * *& FORM ADDSHORTCUTACTION *&--------------------------------------------------------------------- * ADD SHORTCUT ATTACHMENT LAUNCHING TX SWNWIEX ---------------------------------------------------------------------- * FORM ADDSHORTCUTACTION USING P_USER TYPE SYUNAME " USER NAME P_LANGU TYPE SYLANGU " LANGUAGE KEY P_EMAIL TYPE STRING PWIHEADER TYPE SWWWIHEAD " WORKFLOW RUNTIME: HEADER TABLE FOR ALL WORK ITEM TYPES P_ACTION TYPE CHAR40 " ACTION OF TYPE CHAR40 CHANGING PLINENO TYPE I " LINE_NO OF TYPE INTEGERS PTCONTENT TYPE TSOLISTI1TAB PTHEADER TYPE TSOLISTI1TAB PTPACKING TYPE SOPCKLSTI1TAB. *- ADD THE ATTACHMENT TO THE DOCUMENT CONTENT. DATA: LT_ATTACH LIKE SOLISTI1 OCCURS 0. " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 DATA: LT_HEADER LIKE SOLISTIl OCCURS 0 WITH HEADER LINE. " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 DATA: LT_CONTENT LIKE SOLISTIl OCCURS 0. " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 DATA: LT_PACKING LIKE SOPCKLSTIl OCCURS 0 WITH HEADER LINE. " SAPOFFICE: DESCRIPTION OF IMPORTED OBJECT COMPONENTS

DATA: L_CAPTION TYPE STRING. DATA: LACTIONPARAM TYPE TEXT255. " TEXT, 255 CHARACTERS *- TAKE OVER EXISTING LINES LTHEADER[] = PTHEADER[]. LTCONTENT[] = PTCONTENT[]. LTPACKING[] = PTPACKING[]. *- ASSIGN THE APPROPRIATE CAPTION CASE P_ACTION. WHEN CACTIONDISPLAY. L_CAPTION = 'WORKITEM ANZEIGEN'(S06). WHEN CACTIONEXECUTE. L_CAPTION = 'WORKITEM AUSFÜHREN'(S04). WHEN OTHERS. L_CAPTION = 'UNBEKANNTE AKTION'(S03). ENDCASE. *- ASSEMBLE SHORTCUT LACTIONPARAM = P_WIHEADER-WIID. PERFORM CREATESHORTCUTACTION USING PACTION LACTIONPARAM PUSER PLANGU PEMAIL P_LOGON CHANGING LT_ATTACH[]. DESCRIBE TABLE LTATTACH LINES LCOUNT. APPEND LINES OF LTATTACH TO LTCONTENT. *- ATTACHMENT HEADER CLEAR LTHEADER. REFRESH LTHEADER. LT_HEADER = 'WORKITEM.SAP'." FILE NAME APPEND LT_HEADER. CLEAR LT_HEADER. LTHEADER = '&SOFORMAT=ASC'. " THIS INDICATES THAT IT IS ASCII. APPEND LT_HEADER. *- UPDATE THE PACKING LIST. CLEAR LT_PACKING. LTPACKING-HEADSTART = 1. LTPACKING-HEADNUM = 2.

LTPACKING-BODYSTART = PLINENO + 1. LTPACKING-BODYNUM = L_COUNT. LTPACKING-DOCTYPE = 'SAP'. LTPACKING-DOCSIZE = 255 * L_COUNT. LTPACKING-OBJNAME = 'WORKITEM'. LTPACKING-OBJDESCR = L_CAPTION. LTPACKING-OBJLANGU = P_WIHEADER-WILANG. LTPACKING-OBJLANGU = P_LANGU. APPEND LT_PACKING. *- PASS PARAMETERS BACK ADD LCOUNT TO PLINE_NO. PTHEADER[] = LTHEADER[]. PTCONTENT[] = LTCONTENT[]. PTPACKING[] = LTPACKING[]. ENDFORM. " ADDSHORTCUTACTION &-------------------------------------------------------------------*& FORM CREATESHORTCUTACTION &-------------------------------------------------------------------CREATE A SHORTCUT FOR WORKITEM DISPLAY OR EXECUTE --------------------------------------------------------------------- * FORM CREATESHORTCUTACTION USING P_ACTION TYPE CHAR40 " ACTION OF TYPE CHAR40 PACTIONPARAM TYPE TEXT255 " TEXT, 255 CHARACTERS P_USER TYPE SYUNAME " USER NAME P_LANGU TYPE SYLANGU " LANGUAGE KEY P_EMAIL TYPE STRING PLOGONID TYPE TEXT50 " TEXT FIELD CHANGING PTATTACH TYPE SOLITAB. *- CREATE SAP SHORTCUT ATTACHMENT ENTERED( 'CREATEACTIONWA_ATTACH' ). DATA: L_PARAM TYPE TEXT255. " TEXT, 255 CHARACTERS DATA: LLOGONID TYPE TEXT50. " TEXT FIELD DATA: L_SCRAP TYPE TEXT255. " TEXT, 255 CHARACTERS *- ASSEMBLE PIECE FOR EMAIL ADDRESS *- IS REQUIRED WHEN SENDING TO PROXY

IF NOT P_EMAIL IS INITIAL. CONCATENATE '[WORKFLOW]' L_CRLF "#EC NOTEXT 'EMAIL=' P_EMAIL "#EC NOTEXT INTO L_SCRAP. ENDIF. " IF NOT P_EMAIL IS INITIAL *- ASSEMBLE THE PARAMETER STRING *- NOTE 1315354: ADD P_APPL FOR SESSION HANDLING CONCATENATE 'PACTION=' PACTION "#EC NOTEXT '; PWIID=' PACTIONPARAM "#EC NOTEXT '; P_APPL=RSWUWFML2' "#EC NOTEXT '; DYNP_OKCODE=ONLI' "#EC NOTEXT INTO L_PARAM. *- PARAMETER CONVERSIONS LLOGONID = PLOGONID. *- CREATE THE SHORTCUT AS TABLE CALL FUNCTION 'SWNCREATESHORTCUT' EXPORTING I_TRANSACTION = '*SWNWIEX' "#EC NOTEXT I_REPORT = ISYSTEMCOMMAND = IPARAMETER = LPARAM ISAPLOGONID = LLOGONID I_SYSID = SY-SYSID I_GUIPARM = IUSER = PUSER ILANGUAGE = PLANGU I_WINDOWSIZE = 'NORMAL WINDOW' "#EC NOTEXT I_TITLE = ICUSTOM = LSCRAP IMPORTING SHORTCUTTABLE = PTATTACH SHORTCUT_STRING = EXCEPTIONS INCONSISTENT_PARAMETERS = 1 OTHERS = 1.

IF SY-SUBRC 0. REFRESH PT_ATTACH. EXIT. ENDIF. " IF SY-SUBRC 0 LEAVING( 'CREATEACTIONWA_ATTACH' ). ENDFORM. "CREATESHORTCUTACTION &-------------------------------------------------------------------*& FORM GETEMAILADDRESS &-------------------------------------------------------------------GET THE EMAIL ADDRESS FROM VARIOUS SOURCES --------------------------------------------------------------------- * FORM GETEMAILADDRESS USING P_UNAME TYPE SYUNAME " USER NAME CHANGING PADDRESS TYPE TUSER_DATA. INIT EMAIL "NOTE 780623 CLEAR P_ADDRESS. FIRST TRY CENTRAL ADDRESS MANAGEMENT PERFORM GETEMAILADDRESS_CAM USING P_UNAME CHANGING P_ADDRESS. IF THIS FAILED TRY THE AUTO-FORWARDING ADDRESS IF P_ADDRESS-EMAIL IS INITIAL. PERFORM GETEMAILADDRESSAUTOFORW USING PUNAME CHANGING PADDRESS. ENDIF. " IF P_ADDRESS-EMAIL IS INITIAL ENDFORM. "GETEMAILADDRESS &-------------------------------------------------------------------*& FORM GETEMAILADDRESS_CAM &-------------------------------------------------------------------GET ADDRESS DATA FROM THE CENTRAL ADDRESS MANAGEMENT (CAM) --------------------------------------------------------------------- * FORM GETEMAILADDRESS_CAM USING P_UNAME TYPE SYUNAME " USER NAME CHANGING PADDRESS TYPE TUSER_DATA.

*- LOAD USER DATA DATA LT_ADSMTP TYPE TABLE OF BAPIADSMTP. " BAPI STRUCTURE FOR E-MAIL ADDRESSES (BUS. ADDRESS SERVICES) DATA LT_RETURN TYPE TABLE OF BAPIRET2 . " RETURN PARAMETER DATA LS_ADDRESS TYPE BAPIADDR3. " BAPI REFERENCE STRUCTURE FOR ADDRESSES (CONTACT PERSON) DATA L_UNAME TYPE SYUNAME. " USER NAME DATA LS_DEFAULTS TYPE BAPIDEFAUL. " USER: FIXED VALUES TRANSFER STRUCTURE FIELD-SYMBOLS: TYPE BAPIADSMTP. " BAPI STRUCTURE FOR E-MAIL ADDRESSES (BUS. ADDRESS SERVICES) ENTERED( 'GETADDRESS1' ). *- GET THE OTHER THINGS MOVE PUNAME TO LUNAME. CALL FUNCTION 'BAPIUSERGET_DETAIL' EXPORTING USERNAME = L_UNAME IMPORTING DEFAULTS = LS_DEFAULTS " NOTE 849251 ADDRESS = LS_ADDRESS TABLES RETURN = LT_RETURN ADDSMTP = LT_ADSMTP. *- LANGUAGE IF NOT LSADDRESS-LANGUP IS INITIAL. MOVE LSADDRESS-LANGUP TO P_ADDRESS-LANGU. ELSE. " ELSE -> IF NOT LSADDRESS-LANGUP IS INITIAL P_ADDRESS-LANGU = SY-LANGU. ENDIF. " IF NOT LSADDRESS-LANGUP IS INITIAL *- NOTE 849251: LOGON LANGUAGE IF NOT LS_DEFAULTS-LANGU IS INITIAL. MOVE LSDEFAULTS-LANGU TO PADDRESS-LOGON_LANGU. ELSE. " ELSE -> IF NOT LS_DEFAULTS-LANGU IS INITIAL PADDRESS-LOGONLANGU = SY-LANGU.

ENDIF. " IF NOT LS_DEFAULTS-LANGU IS INITIAL *- EMAIL ADDRESS *- USE STANDARD EMAIL ADDRESS (NOTE 746911) READ TABLE LTADSMTP WITH KEY STDNO = 'X' ASSIGNING . IF SY-SUBRC = 0. MOVE -EMAIL TO PADDRESS-EMAIL. ELSE. " ELSE -> IF SY-SUBRC = 0 *- USE ANOTHER EMAIL ADDRESS READ TABLE LT_ADSMTP ASSIGNING INDEX 1. IF SY-SUBRC = 0. MOVE -EMAIL TO PADDRESS-EMAIL. ENDIF. " IF SY-SUBRC = 0 ENDIF. " IF SY-SUBRC = 0 LEAVING( 'GET_ADDRESS1' ). ENDFORM. "GETEMAILADDRESS &-------------------------------------------------------------------*& FORM GETEMAILADDRESSAUTOFORW &-------------------------------------------------------------------GET E-MAIL ADDRESS FROM AUTO-FORWARDING --------------------------------------------------------------------- * FORM GETEMAILADDRESSAUTOFORW USING P_UNAME TYPE SYUNAME " USER NAME CHANGING PADDRESS TYPE TUSER_DATA. *- COMPUTE EMAIL ADDRESS FROM AUTO-FORWARDING DATA L_UNAME TYPE SYUNAME. " USER NAME DATA LCOMART TYPE SOCOM_ART. " SAPOFFICE: COMMUNICATION METHOD DATA LADDRESS TYPE SOREC_EXT. " EXTERNAL ADDRESS (SMTP/X.400... ) MOVE PUNAME TO LUNAME. CALL FUNCTION 'SOAUTOMATICFORWARD_GET' EXPORTING USER = L_UNAME IMPORTING ADDRESS = L_ADDRESS COMART = L_COMART

EXCEPTIONS SUBSTITUTENOTACTIVE = l X_ERROR = 2 OTHERS = 3. IF SY-SUBRC = 0. IF LCOMART = CCOMTYPEINT. PADDRESS-EMAIL = LADDRESS. ENDIF. " IF LCOMART = CCOMTYPEINT ENDIF. " IF SY-SUBRC = 0 ENDFORM. "GETEMAILADDRESSAUTOFORW &-------------------------------------------------------------------*& FORM STRINGTOTABLE &-------------------------------------------------------------------CONVERT STRING TO SO TABLE --------------------------------------------------------------------- * FORM STRINGTOTABLE USING P_STRING TYPE STRING CHANGING PTABLE TYPE SOLITAB. DATA: LS_SOLI TYPE SOLI, " SAPOFFICE: LINE, LENGTH 255 L_STRLEN TYPE I, " STRLEN OF TYPE INTEGERS L_STRING TYPE STRING. CLEAR P_TABLE. LSTRING = PSTRING. LSTRLEN = STRLEN( LSTRING ). CHECK L_STRLEN NE 0. LONGER THAN ONE LINE WHILE L_STRLEN GT 255. LSSOLI = LSTRING. APPEND LSSOLI TO PTABLE . SHIFT L_STRING BY 255 PLACES. LSTRLEN = STRLEN( LSTRING ). ENDWHILE. LSSOLI = LSTRING. APPEND LSSOLI TO PTABLE. ENDFORM. "STRINGTOTABLE

*&-------------------------------------------------------------------- * *& FORM TABLETOSTRING *&-------------------------------------------------------------------- * CONVERT SO TABLE TO STRING --------------------------------------------------------------------- * FORM TABLETOSTRING USING PTABLE TYPE SOLITAB CHANGING P_STRING TYPE STRING. DATA: L_STRING TYPE STRING. FIELD-SYMBOLS: TYPE LINE OF SOLI_TAB. TRICK 17 LOOP AT P_TABLE ASSIGNING . CONCATENATE LSTRING ' ' INTO LSTRING SEPARATED BY . ENDLOOP. " LOOP AT P_TABLE ASSIGNING REMOVE TRAILING SPACES SHIFT L_STRING RIGHT DELETING TRAILING SPACE. SHIFT L_STRING LEFT DELETING LEADING SPACE. MOVE LSTRING TO PSTRING. ENDFORM. "TABLETOSTRING &-------------------------------------------------------------------*& FORM TLINETOSTRING &-------------------------------------------------------------------CONVERT SAPSCRIPT TABLE TO STRING --------------------------------------------------------------------- * FORM TLINETOSTRING TABLES P_TABLE "LIKE TLINE OCCURS 0 CHANGING P_STRING TYPE STRING. DATA: L_STRING TYPE STRING. FIELD-SYMBOLS: TYPE TLINE. " SAPSCRIPT: TEXT LINES TRICK 17 LOOP AT P_TABLE ASSIGNING .

CONCATENATE LSTRING -TDLINE LCRLF INTO L_STRING. ENDLOOP " LOOP AT P_TABLE ASSIGNING REMOVE TRAILING SPACES SHIFT L_STRING RIGHT DELETING TRAILING SPACE. SHIFT L_STRING LEFT DELETING LEADING SPACE. MOVE LSTRING TO PSTRING. ENDFORM. "TLINETOSTRING &-------------------------------------------------------------------*& FORM GET_DOCUMENT &-------------------------------------------------------------------RETRIEVE TEXT CREATED WITH SE61 --------------------------------------------------------------------- * FORM GETDOCUMENT USING PTYPE LIKE DOKHL-ID " DOCUMENT CLASS P_OBJECT LIKE DOKHL-OBJECT " DOCUMENTATION OBJECT P_LANGU TYPE SYLANGU " LANGUAGE KEY CHANGING P_TEXT TYPE STRING. DATA: LSDOCUHEAD LIKE THEAD . " SAPSCRIPT: TEXT HEADER DATA: LT_TLINE TYPE TABLE OF TLINE. " SAPSCRIPT: TEXT LINES DATA: LT_STREAM TYPE TABLE OF SOLISTI1. " SAPOFFICE: SINGLE LIST WITH COLUMN LENGTH 255 IF P_OBJECT IS INITIAL. EXIT. ENDIF. " IF P_OBJECT IS INITIAL GET TEXT IN SAPSCRIPT FORMAT CALL FUNCTION 'DOCU_GET' EXPORTING ID = P_TYPE LANGU = P_LANGU OBJECT = P_OBJECT IMPORTING HEAD = LSDOCUHEAD TABLES LINE = LT_TLINE EXCEPTIONS

OTHERS = 1. ERROR HANDLING IF SY-SUBRC 0. MESSAGE ID 'S4' TYPE 'E' NUMBER '601' WITH P_TEXT SY-LANGU. " OBJECT & IN LANGUAGE & DOES NOT EXIST EXIT. ENDIF. " IF SY-SUBRC 0 REPLACE INCLUDES CALL FUNCTION 'TEXTINCLUDEREPLACE' EXPORTING HEADER = LSDOCUHEAD TABLES LINES = LT_TLINE. NOTE l506337: REPLACE COMMANDS CALL FUNCTION 'TEXTCONTROLREPLACE' EXPORTING HEADER = LSDOCUHEAD PROGRAM = ' ' REPLACE_COMMENT = 'X' IMPORTING CHANGED = NEWHEADER = TABLES LINES = LT_TLINE. REPLACE VARIABLES CALL FUNCTION 'TEXTSYMBOLREPLACE' EXPORTING HEADER = LSDOCUHEAD TABLES LINES = LT_TLINE. FORMAT INTO TEXT STREAM CALL FUNCTION 'CONVERTITFTOSTREAMTEXT' TABLES ITFTEXT = LTTLINE TEXTSTREAM = LTSTREAM. IF LT_STREAM[] IS INITIAL.

INSERT SPACE INTO LT_STREAM INDEX l. ENDIF. " IF LT_STREAM[] IS INITIAL CONVERT TO STRING. PERFORM TABLETOSTRING USING LTSTREAM CHANGING PTEXT. ENDFORM. "GET_DOCUMENT *&-------------------------------------------------------------------- * *& FORM GETDYNPROVALUE *&-------------------------------------------------------------------- * GET VALUE OF A PARTICULAR FIELD ON THE SELECTION SCREEN --------------------------------------------------------------------- * FORM GETDYNPROVALUE USING P_FIELD CHANGING P_VALUE. DATA: BEGIN OF DYNP_TAB OCCURS 1. INCLUDE STRUCTURE DYNPREAD. " FIELDS OF THE CURRENT SCREEN (WITH VALUES) DATA: END OF DYNP_TAB. DATA: L_REPID LIKE SY-REPID. CLEAR DYNPTAB. REFRESH DYNPTAB. DYNPTAB-FIELDNAME = PFIELD. DYNP_TAB-STEPL = 0. APPEND DYNP_TAB. L_REPID = SY-REPID. CALL FUNCTION 'DYNPVALUESREAD' EXPORTING DYNAME = L_REPID DYNUMB = '1000' TRANSLATETOUPPER = ' ' TABLES DYNPFIELDS = DYNP_TAB EXCEPTIONS OTHERS = 1. IF SY-SUBRC NE 0. EXIT. ENDIF. " IF SY-SUBRC NE 0 PVALUE = DYNPTAB-FIELDVALUE.

ENDFORM. "GETDYNPROVALUE *&-------------------------------------------------------------------- * *& FORM SELECTMODIFIEDWORKITEMS *&-------------------------------------------------------------------- * RETRIEVE SWWLOGHIST ENTRIES WHICH CONTRIBUTE --------------------------------------------------------------------- * FORM SELECTMODIFIEDWORKITEMS. DATA: LT_SWWLOGHIST TYPE STANDARD TABLE OF SWWLOGHIST. " WORKFLOW RUNTIME: HISTORY OF A WORK ITEM DATA: LR_METHOD TYPE RANGE OF FUNCNAME. " FUNCTION NAME DATA: LSMETHOD LIKE LINE OF LRMETHOD. DATA: LTWILOG TYPE TWIDATA OCCURS 0 WITH HEADER LINE. FIELD-SYMBOLS: TYPE SWWLOGHIST. " WORKFLOW RUNTIME: HISTORY OF A WORK ITEM *- FILL THE LIST OF ACTIONS AFFECTING WORKITEMS IN OUR SENSE LS_METHOD-SIGN = 'I'. LS_METHOD-OPTION = 'EQ'. LSMETHOD-LOW = 'SWWWI_FORWARD'. APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SWWWI_BACK'. APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SWWWIRESUBMISSIONEND'. APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SWWWI_STATUSSETREADY'. APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SWDADHOCAGENTINSERT'. "NOTE 1177811 APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SWWWIAGENTSCHANGE'. " NOTE 1177811 APPEND LSMETHOD TO LRMETHOD. *- NOTE 911750 LSMETHOD-LOW = 'SAPWAPIFORWARDWORKITEM'. APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SAPWAPI_PUTBACKWORKITEM'. APPEND LSMETHOD TO LRMETHOD. LSMETHOD-LOW = 'SAPWAPI_SETWORKITEMSTATUS'. APPEND LSMETHOD TO LRMETHOD.

LSMETHOD-LOW = 'SAPWAPIENDRESUBMISSION'. APPEND LSMETHOD TO LRMETHOD. *- SELECT IN SWWLOGHIST SELECT WI_ID TIMESTAMP FROM SWWLOGHIST " WORKFLOW RUNTIME: HISTORY OF A WORK ITEM INTO CORRESPONDING FIELDS OF TABLE LT_SWWLOGHIST WHERE TIMESTAMP GT LFROMTSTAMP AND TIMESTAMP LE LTOTSTAMP AND METHOD IN LR_METHOD. CHECK LT_SWWLOGHIST IS NOT INITIAL. *- WE NEED ONLY ONE ENTRY SORT LTSWWLOGHIST BY WIID. DELETE ADJACENT DUPLICATES FROM LTSWWLOGHIST COMPARING WIID. *- SELECT HEADER WITH RANGE TAB FILTERING BY TASK SELECT WI_ID TCLASS FROM SWWWIHEAD " WORKFLOW RUNTIME: HEADER TABLE FOR ALL WORK ITEM TYPES INTO CORRESPONDING FIELDS OF TABLE LTWILOG FOR ALL ENTRIES IN LT_SWWLOGHIST WHERE WIID EQ LTSWWLOGHIST-WI_ID AND WISTAT = WISTATUS_READY " NOTE l073097 AND WIRHTASK IN TASK_SEL. *- MERGE WITH EXISTING ID TABLE APPEND LINES OF LTWILOG TO LTWIDATA. *- REMOVE DUPLICATES SORT LTWIDATA BY WI_ID. DELETE ADJACENT DUPLICATES FROM LTWIDATA COMPARING WI_ID. ENDFORM. "SELECTMODIFIEDWORKITEMS &--------------------------------------------------------------------*& FORM CONVERT_HEADER &--------------------------------------------------------------------CONVERT HEADER FORMATS ---------------------------------------------------------------------- * -->P_HEAD SWWWIHEAD View with error indicators, in order to display the errors, which are indicated in the log with the symbol

By clicking on the error symbol, the system displays an analysis of the error which may describe the cause of the error. You can access the information contained in this analysis.

Monitoring and Analysis Tools Monitoring can be done using the standard reports that are available in the system. For instance, you can search for SAP Workflows that contain a particular task, component or for SAP Workflows started in a defined period of time (today, last week, last month, last year, all). A short overview of the main transaction is provided here. 1.125 WORK ITEM MONITORING Transaction code SWI1: Searching and displaying Work Items of all types – You can search and display work items of all types according to various criteria to check status.

Press F8 key.

Transaction code : SWI2_FREQ - Searching and displaying Work Items per Task: You can search and display work items grouped per task and display work items of the same task.

Press F8 key.

Transaction code : SWI2_ADM1 — Searching and displaying Work Items without agents -You can search and display work items without agents to determine next actions.

Press F8 key. Example:

Transaction code: SWI6 — Searching and displaying Work Items with object type. You can search and display work items with specific Business Object instance and to analyze the status of SAP Workflow.

Choose Object Type from the Repository:

1.126 ERROR MONITORING, ANALYSIS AND RESTARTING Transaction code: SWI2_DIAG: Listing Work Items with errors and displaying error diagnosis. You can list work items by cause of error.

Press F8 key.

Double click to get Error Details.

Transaction code: SWUD: SAP Workflow Diagnosis. You can use this transaction for SAP Workflow Diagnosis which is very useful if you discover that a particular SAP Workflow is not working correctly.

Transaction code: SWPR: Restarting SAP Workflow - You can restart SAP Workflows after error. Keyin the Workltem ID to be restarted after Error (once Error is corrected)

Transaction code: SWPC: Continuing SAP Workflow - You can continue SAP Workflows that hang after a system crash. Keyin the Workltem Id to be restarted whichs hung due to system crash.

1.127 WORKFLOW ERROR LOG NOTIFICATION Reference — Piyush Agarwal Artefact

Purpose The basis for this whitepaper is a Proof-of-Concept (PoC) in the SAP ABAP Workflow. It was done for a customer who manages through the SAP portal, all organization actions using HCM Process and Forms. Once the form is landing in ERROR status, it's losing visibility. We have the risk of overpayments for the terminated employees as well. This whitepaper shows how to aid manual monitoring by an automatic notification to the initiator and IT support team of the workflow error log. Introduction The underlying PoC was done for a customer who manages his HR worldwide through the HCM HCM Process and Forms for all organization actions. Due to unforeseen issues like data error, incorrect or missing agent, etc., the forms land in error. These errors prevent the possibility to auto approve the workflow, and require that the form be initiated again from the portal. Once the form is landing in ERROR status, due to manual monitoring it's losing the visibility. We have the risk of overpayments for the terminated employees as well. While SWIA can be used to list work items in ERROR status, this report needs to be extracted manually and monitored. This manual activity of error log monitoring takes up at least 5-6 hours of effort every week. As an initiative to reduce manual monitoring work and to automate the process, this solution is proposed: Email should be sent to initiator and IT support team for all errors in SWIA, preventing any human errors of not extracting the error log.

Problem Statement Once the form is landing in ERROR status, due to manual monitoring it's losing the visibility. We have the risk of overpayments for the terminated employees as well. SWIA can be used to list work items in ERROR status, this report can be extracted manually. This manual activity of error log monitoring takes up at least 5-6 hours of effort every week.

To extract this report, a one would need to access SWIA daily and pull this error log and notify relevant people of the failed workflows. Solution Report RSWIWILS is the calling program for the SWIA output screen. A custom report can be created as a copy of this standard report, daily job can be scheduled saving a variant with status ERRORS. The selection screen can be updated to add new fields for email address input. IT support team email addresses can be passed from the selection screen. Initiator email address can be extracted from the output of SWIA. Initiator user ID (IT0105 subtype 0001) can be extracted from column Creator. To identify initiator, we can use the rows for which cells in column Workflow are blank. Initiator user ID would be extracted as char 3 onwards of column Creator. Through initiator user ID, initiator email address can be extracted from IT0105 — subtypes 0001 and 0010. Email address of initiators can be appended into the table holding selection screen input of email addresses. Email generated can have a .xls attachment of the required output format (either all fields or selected fields of SWIA output). Technical Steps In this document, we create a report that has the same look and feel as SWIA, but this report will generate an email listing all the work items in status ERROR and send the email to all recipients required. To achieve this, we need to copy a standard SAP program and make some minor adjustments. Step 1. Copy the SAP report. SE38: Copy program RSWIWILS to ZRSWIWILS. Activate the program. Then, in the attributes, change the title of the program to Workflow Error Log Notification Report.

(If you see a message about Different original and logon languages then click on the Change orig. language button and continue to agree with whatever SAP asks until you get to the ABAP: Program Attributes ZRSWIWILS Change window, where you can change the Title.) Step 2. Create a new report transaction. SE93: Create a 'report transaction' ZWFERRORNOTIF and link it to program ZRSWIWILS.

Step 3. Edit the program. SE38: Make some code changes to ZRSWIWILS — see attached document. (We add the additional logic at two places:

Step 5. Test the program. You can test it by running transaction ZWFERRORNOTIF. The selection screen is the same as SWIA with the addition of the email address input:

The output will be an email generated with all the work items in ERROR. Step 6. Setup a job for the program. SM37: Create a new job for daily run. The workflows in ERROR will be automatically notified to the relevant people, and manual monitoring is no longer required. NOTE

2 chapter Automated Workflow Monitoring What do you find in this chapter? 2.1 PURPOSE OF THE DOCUMENT This documentation contains specifications, development details, and test results of the Automated Workflow Monitoring Program developed in SR5. 2.2 BENEFITS TO BUSINESS Currently we do workflow monitoring by using standard transaction codes SWPR, SWPC, SWI1, SWI2_ADM1. Determining the corresponding

action and performing the action requires a Significant amount of time. There are also errors that require separate checks and effort gets multiplied when there are a hundred or more of this specific error. Automated Workflow Monitoring will save time to manually monitoring transaction codes. This send auto generated mail to Client Support Center team for creating Service order against correct service Group based on the error occurring in the workflow. This will save a lot of manual effort and human mistake. This will save monthly 40 to 60hrs of work. 2.3 ATTRIBUTES OF DEVELOPED REPORT 2.4 TECHNICAL DETAILS Specifications: Automate WF monitoring using transactions: SWPR, SWPC, SWI1, SWI2_ADM1 Enable email function to raise Service Order to CSC. The maximum workitems that can be included in an email is set to 6. Perform required actions, e.g. For error — Order Cancelled and TECOed, check if status is TECO, refer to testing section. Limitation: Logically delete of WIs is not included Table Created: ZCA_WFMONITOR Transaction for table maintenance: ZTAB_WFMONITOR This will contain the details on SAP Workflow Production Monitoring file — FAQ sheet. (See Reference Document Section)

See entries below (captured from FAQ tab of monitoring file).

FAQ tab of monitoring file:

Standard text: ZCAWFSOEMAIL This text contains the email template when raising an SO to the CSC team. Variable values (&) will be replaced upon executing the "WF monitoring program. The maximum work items that can be included in an email is set to 6.

Program: ZCAWFMONITORING Transaction: ZWFMONITORING

Selection screen details: 2.5 TEST RESULTS

Results are displayed in ALV. Error PM60 : Notification 900138111 exceeded Expend. Limit is maintained in the "WF error table, the program identified which team handles the SO and email was sent. If the error is not found in the table then Result column is blank. The count of errors are displayed in the header, it will only include items with Result — Email sent.

Email in SOST transaction and suncor mail. This email can now be forwarded to CSC team.

Upon checking SWI1, program was able to retrieve the same errors given the same creation date. Only main workitem IDs are processed in the program.

Results are displayed in ALV. For errors Order Cancelled and TECOed, the status of the orders were checked (required action = X) and results are displayed — TECO status, logically delete this workitem. The count of errors are displayed in the header, it will only include items with Result — Email sent.

Email from SOST transaction and suncor mail:

Upon checking SWI1, program was able to retrieve the same errors given the same creation date. Only main workitem IDs are processed in the program.

Results are displayed in ALV. The count of errors are displayed in the header, it will only include items with Result — Email sent.

Email form SOST transaction and suncor mail:

SWI1 errors from monitoring program:

Upon checking SWI1, program was able to retrieve the same errors given the same creation date. Only main workitem IDs are processed in the program, SWI1 has 46 entries, not all of these are main WI IDs. When the same errors are returned by the other transactions, it will not be processed.

SWPC workitems from monitoring program:

SWPC tcode, program was able to retrieve the same error given the same creation date.

There are no SWPR workitems from monitoring program. SWPR tcode, in the program there are 0 errors from SWPR since all of these errors are already returned by SWI1.

SWI2_ADM1 items from monitoring program:

SWI2_ADM1 tcode, program was able to retrieve 4 errors.

Results are displayed in ALV. The count of errors are displayed in the header, it will only include items with Result — Email sent.

Email form SOST transaction and suncor mail:

Upon checking SWPR tcode, program was able to retrieve the same errors given the same creation date.

Results are displayed in ALY There are no errors from SWPC transaction, all of the work item texts retrieved are not maintaned in ZCA_WFMONITOR table, no action was done by the program (Result column is blank).

Check workitems from SWPC tcode, same items were retrieved in monitoring program.

Results are displayed in ALY There are no errors from SWI2ADM1 in monitoring program, since work item texts below is not maintained in ZCAWFMONITOR table.

SWI2_ADM1 tcode workitems, given the same date interval the results match with monitoring program.

From scenario 6, there are no errors retrieved and the program did no action since the error text is not maintained in ZCA_WFMONITOR table. But going to the SAP WF Production Support file, in FAQ sheet this error is logged.

Maintain this new error in the table, go to transaction code ZTAB_WFMONITOR.

Use the next available WF ID, enter error text, action required and team responsible. Save this entry.

The table now has new error.

Run the WF monitoring program again with details same with Scenario 6 — SWI2_ADM1.

Results are displayed in ALV. There are 3 errors now from SWI2_ADM1 and an email was sent to raise SO.

Email from SOST and XXX mail.

SWI2_ADM1 tcode workitems, given the same date interval the results match with monitoring program.

Sign Off for PRD (30) : 2.6 REFERENCE DOCUMENTS SAP Workflow Production Monitoring file — FAQ sheet. Sample Monitoring Steps

Sample Tools

Sample Issue Log FAQs Screenshots:

NOTE

3 chapter SAP Business Workflow Terminology What do you find in this chapter? 3.1 PURPOSE The purpose of this document is to give a brief description of the Business Workflow Terminology. 3.2 GLOSSARY Activity

Step type in a workflow definition for executing a task at runtime. The task can be a single-step task (customer task/standard task) or a multi-step task (workflow task/workflow template). At runtime, an activity is represented by a work item of one of the following types: Actual Agent Recipient of a work item who processes (or has processed) it. Advance with immediate dialog Execution property of the workflow system. A work item for which this indicator is set, is executed immediately if the actual agent of the preceding dialog work item is also a recipient of this work item. This user does not have to call their Business Workplace to execute the work item. Agent Super ordinate term for a system user who participates actively in SAP Business Workflow and whose activities include the execution of work items. There are various types of agent: Attribute Property or characteristic of an object. An attribute is an object type component. The attributes of an object are specified and implemented as part of the object type definition in the Business Object Repository. Conditions can be formulated with attributes in the workflow definition. At runtime, the attribute values are read/calculated and can also be used to control the workflow. Object type attributes can provide data in the following forms: Key fields are also attributes of the object type. They are used to identify an object as well. Examples of attributes of the object type MATERIAL: Approval task Single-step task that executes an approval method with a result. The result must be able to assume at least two values, one of which stands for approval and the other for rejection of the object processed. For the extended approval procedure, the approval method must be able to assume two more values, one for proposed approval and the other for proposed rejection. Background Work item Type B work item that represents a task whose execution does not require any dialog and can therefore be controlled by the workflow system. Background work items are not displayed in the Business Workplace, but can be found using the selection report for work items of all types. Binding Assignment of values to a container element at runtime. The assignment rules to be observed are specified beforehand in the binding definition. Binding Definition Specification of assignment rules describing the assignment of data to a container element (initial value assignment) or the exchange of data between two container elements. Block Elementary structure element of a workflow definition. A block always contains a consistent arrangement of steps and operators. A block has one beginning and one end. The consistency and robustness of a workflow definition is ensured by the fact that a block is always created when a new step is created or an undefined step changed. Similarly, when individual steps are deleted, cut or inserted, the entire block in which the step is located, is affected. Business Object Builder (Transaction SWO1) Tool for creating and processing business object types. You can use the Business Object Builder for direct access to the definition of an object type. You can also check and generate the business object type, as well as get a where-used list. You can also create subtypes for an existing business object type. Business Object repository

Directory of all object types in a hierarchy format. The object types are each assigned to a package (and hence indirectly to an application component as well). Business Object Type Generic definition of a business object. It describes the characteristics, and common attributes of each instance of an SAP business object. Business Workflow Explorer Tool for executing the following functions: Business Workplace / SAP Office (Transaction Code SO01) A user's integrated work area for: Check Function Module Function module that can be used to prevent a linkage being triggered when an event occurs. It is called synchronously in the Logical Unit of Work (LUW) of the event creator by the event manager directly before the receiver function module is called if: The check function module and the receiver function module have the same interface. This means that the content of the event container can be checked and the calling of the receiver function module prevented. If the check function module terminates with an exception, the receiver function module is not called and the linkage between the event and the receiver not established. Condition Step type in a workflow definition for processing one of two defined branches in the workflow definition at runtime. The workflow system makes the decision based on defined conditions and information contained in the workflow container as values. You define conditions using the condition editor, which enables you to implement even complex and multilevel conditions. Container Basic common data structure of the various definition components and execution components of SAP Business Workflow. Containers have container elements for holding the following: The container elements can be used to control the execution of work items and workflows. The container elements are addressed using an identifying name, and may consist of several lines. Container Definition General information about the structure of the data to be stored in a container. A container definition specifies which container elements a container holds, and with which properties (ID, name, data type). Container definition always takes place when working with one of the definition tools (in object type definition, role definition, task definition, workflow definition). Container Element Entry in a container. A container element is defined by its ID, name, and data type reference. Container Operation Step type in a workflow definition for performing elementary arithmetic operations or value assignments on individual elements of the workflow container at runtime. Creation Date/Time Point in time at which a work item was first created with the status ready or waiting. The latter applies if a requested start was declared for the work item. Current Agent

User who processes (or has processed) a work item. The current agent of a work item is therefore one of the recipients of a work item. Deadline Monitoring Workflow runtime system function that monitors the start deadlines and end deadlines for the processing of selected work items. In deadline monitoring, the deadline notification agents are notified with a missed deadline work item. Deadlines Determination of deadlines for step types activity, user decision and wait step. Specifying deadlines is optional. Decision Option List of possible options that are offered to the actual agent of a user decision. There is a branch with modeled steps in the workflow definition for each of the decision options. One of these branches is processed at runtime in accordance with the user decision. Decision Task Single-step task with which the workflow system executes a user decision in the workflow. The method PROCESS of object type DECISION is always executed with a decision task. Decision tasks only differ in the following ways: The decision task TS00008267 (generic decision task) supplied by SAP is used as standard in a user decision. You can specify another decision task in the definition of a user decision. Alternatively, you can define in customizing that another decision task is to be used as standard. Dialog Work item Type W work item, which at runtime represents a workflow step or a task that requires dialog with the user. Dialog work items are usually displayed in the Business Workplace. When a dialog work item that is based on a task is executed, the underlying object method is called. It is possible to monitor deadlines for dialog work item execution. Event Occurrence of a change of state in an object, which is published throughout the system. An event is an object type component. The list of possible events is defined with the relevant object type in the Business Object Builder. This list can be extended according to customer requirements using the delegation concept. The actual creation of the events added must be catered for. Each event carries information from its creation context in its event container. This information is available to the receiver of the event and can be used for event-driven control and communication mechanisms. Events can start, terminate or continue tasks and workflows. Examples of events: Container that contains the event parameters of an event. The event must be defined as an object type component in the Business Object Repository (BOR). Event containers can have bindings with workflow containers or task containers. Event Creation Program or environment in which an event is created. An event can be created in various ways: The last three creation mechanisms listed can also be used by customers. This means events can be created flexibly and on a customer-specific basis even where the option has not been provided by SAP in the standard version. An event can only be created if it is defined as a component of an object type in the Business Object Repository. Event Creator

Step type in a workflow definition for creating an event at runtime. Event Parameter Runtime information from the event creation context. Event Receiver Super ordinate term for the combination of receiver function module, receiver type and possible object data. The event receiver is started by the event manager, and reacts to the occurrence of an event. When an event occurs, the event manager evaluates all active linkages. If linkages that are to react to the event are found, the relevant receiver function module is started. This may start a workflow (specified in the receiver type) or continue a work item, for example. Excluded Agent User who is excluded from processing a work item. Excluded agents can be determined at runtime so that information from the workflow execution environment (such as agents of previous steps) or from the context of the application objects processed can be considered. Expression Common superordinate term for constant, variable and system field. These terms have the following meanings in the expression context: Constant Variable System field Field from table SYST Expressions are used, for example, to describe the origin and/or destination of the data to be transferred in a binding definition. General task Indicator for a task or a workflow. Tasks and workflows with this indicator can be executed or started by any user. The following apply to the associated work items: Implementation Program ABAP program containing the implementation of methods and attributes of the object type. When the attributes, methods and events are defined, the interface of the object type is described, and all essential information about the object type is documented. Every object type requires one program, containing the following: This collection of subroutines is then accessed by the function modules of the runtime environment to call methods and read attribute values. The implementation program is partly created automatically by the system from the definition information. Some post processing is required, however. Loop Step type in a workflow definition for repeating a sequence of steps at runtime. UNTIL and WHILE loops are available. Method Operation that can be executed on an object. A method is an object type component. The methods of an object type are specified and implemented in the Business Object Builder. Methods usually refer to existing ABAP functions, such as function modules, transactions, and dialog modules. They are called using a standard interface, which is determined basically by the method

ID and the method parameters. The actual implementation of a method is not apparent externally. You can specify the following for synchronous methods: You can only specify import parameters for asynchronous methods. Method Parameter Container that contains the method parameters of a method. The method must be defined as an object type component in the Business Object Builder. A binding from the task container to the method container is required for task execution. Export parameters of the method can be passed from the method container to the task container with a binding. A method container is not persistent. Missed Deadline work item Work item for notifying the deadline notification agents if the runtime system discovers a missed deadline for a work item. The notification takes place in the form of a type D work item in the integrated inboxes of the relevant recipients. The recipients are specified when step is defined. The notification text is entered when the task to be monitored is defined. When a missed deadline work item is executed, the most important information about the monitored work item is displayed. Multistep Task Step type in a workflow definition for processing one of several defined branches of the workflow definition at runtime. This is based on information from the context of the workflow or the objects processed. The value of the basis of comparison (expression from workflow container) is compared with the comparison values. Organizational Object Instance of an SAP organizational object type defined in the Business Object Repository (BOR). SAP organizational object types (sometimes known as SAP OrgObject types) represent organizational entities at the object type level in the BOR. These entities are used to collect and describe employee groups in a way. Possible Agent User who is organizationally authorized to start a task and execute the relevant work item. The possible agents are not usually expressed with a full list of all user names, but with organizational units, positions and jobs. The possible agents of a task are specified in the task definition. Without possible agents, a task cannot be executed or started in dialog. Process Control Step type in a workflow definition for performing the following operations at runtime: Responsible Agent User assigned to a step in the step definition. Expressions, organizational objects, or roles can also be used to assign the responsible agents. The system determines the recipient(s) of a work item from the intersection of responsible and possible agents. Role Rule for determining users at runtime. These can be used as responsible agents or as recipients of notifications. A role can be defined using: Role Resolution Determination of all users who have the property described by the role. The role resolution takes place at runtime using information from the respective process running. Example:

The example refers to the role Employee responsible for customer for order amount . At workflow runtime, if there is an order with amount USD 34,569.34 for customer Smith Inc., the agents who are Employees responsible for customer Smith Inc. for order amount USD 34,569.34 are determined. Rule Container Container that contains the parameters of a rule for agent determination. Rules of this kind can be used to determine responsible agents for a work item at workflow runtime. To assign values to the container elements of the rule container, a binding is required from the workflow container or task container to the rule container. A rule container is not persistent. SAP Business Workflow SAP application component that comprises technologies and tools for automated control and editing of cross-application processes. This primarily involves coordinating: The main aims are to cut lead times and the costs of business processes, and to improve transparency and quality. Send Mail Step type in a workflow definition for sending an email to internal or external recipients at runtime. The step definition contains all the input fields required to define the email. Single-Step Task Task described by a object method. Single-step tasks can be split into standard tasks and customer tasks, which differ as follows: Standard Task Customer Task Only standard tasks will be supported in the future. Standard Task Single-step task for use in workflow definitions. You can execute methods of business object types in standard tasks. The following apply to standard tasks: Step Elementary module of a workflow definition. The following types of step exist: The individual steps are arranged and processed sequentially. Only steps in forks can be executed simultaneously. Steps within a workflow definition can only be changed or inserted according to certain rules, considering block orientation.

When you create a step in a workflow definition, you must specifiy the step type first. The following step types exist: The steps can be arranged in series or in parallel processing (fork). The processing sequence of the steps depends on the result of each preceding step. The possible results of a step are usually derived from the relevant business function and are specified in the workflow step on the Outcomes tab. The system adds another branch to the processing chain for each possible outcome. Depending on their type, all steps and events have certain symbols in the graphical display. Substitute Profile Collection of a substitute's rights. A substitute profile is assigned to a substitute when the substitution is set up. A substitute profile combines many task classes. Task classes are assigned to single-step tasks during definition. Substitute profiles are defined and task classes combined to form substitute profiles in Customizing. Sub Workflow Workflow referenced in an activity in a workflow definition. At runtime, the workflow specified in the activity is executed when the step is executed. Subtype Copy of an object type, which has inherited all attributes, events, and methods. The subtype can be modified and extended. Subtypes are used to edit or extend object types supplied by SAP Synchronous Method Method that assumes process control for the duration of its execution and reports back to the calling component (in this case the work item manager) after its execution. Terminating events can be defined for a task described by a synchronous object method. At runtime, the relevant work item is completed either when the method has been processed or when one of the events occurs.

A synchronous method can return the following data to the workflow: Table Element Multiline element in the workflow container, which can contain a list of values. A table element can be specified in activity definition. The activity is then executed in parallel processing branches as many times as there are values in the table. Task Description of a business activity with a specific purpose. The following tasks exist in the workflow context: Single-step task (customer task/standard task) Activity in which an object method is executed on a specific object. Multistep task (workflow task/workflow template) Activity whose description refers to a workflow definition. Task Container Container of a task for storing data from the task environment. The task container contains the control information in the form of constants and object references: The task container contains some predefined workflow system elements. You can define more container elements in the task container, such as required for variable replacement in texts. A task container is also known as a work item container at runtime. Task Group Collection of standard tasks, workflow templates and other task groups, which are used in a common context. You can set up hierarchies of task groups by inserting task groups into other task groups. Task groups can be cross-application. They can include tasks from within one application component as well as tasks from different application components Terminating Event Event whose occurrence completes a task. If the indicator Confirm end of processing is set for the task, the end of processing must be confirmed by a recipient after the event has occurred as well. The event is entered as a terminating event in the task definition. A task can have several terminating events. Tasks that refer to an asynchronous method must have at least one terminating event. Tasks that refer to a synchronous method can have terminating events. Tasks with a terminating event are completed as follows: Triggering Event Event whose occurrence starts a task or a workflow. The event must be entered as a triggering event for the task or workflow that is to be started. The event linkage must be activated. A task or workflow can have several triggering events. Information from the event creation context can be passed in the binding from the event container to the task container or workflow container. The event must be defined as an object type component in the Business Object Builder. UNTIL Loop Step type in a workflow definition for processing a sequence of steps repeatedly at runtime until the termination condition defined in the loop command applies.

The system makes the decision about terminating the loop based on a termination condition created in the condition editor, in conjunction with values contained in the workflow container. The first check takes place after the loop has been processed once. User Decision Step type in a workflow definition for taking a branch at runtime based on a decision made by the actual agent during the current workflow. At runtime the user decision is represented by a dialog work item (type W work item). Virtual Attribute Attribute for which a read procedure always must be implemented, since no field content in the database corresponds to this attribute. Its value is established by evaluating what may be complex database contents at runtime. It is generally the case that multiline attributes and attributes that refer to an object with several key fields are to be implemented as virtual attributes. A virtual attribute can return the value of an ABAP Dictionary field or an object reference. Wait Step Step type in a workflow definition for waiting for an event at runtime. Processing in this workflow branch is not continued until the expected event has occurred. At runtime, a wait step is represented by a wait step work item (type E). WHILE Loop Step type in a workflow definition for processing a sequence of steps repeatedly at runtime if the comparisons defined in the step definition apply. To make the decision, the workflow system compares the value of a basis of comparison (= expression from the workflow container) with the defined comparison values. The first check takes place before the loop is processed. Work Item Runtime representation of a task or a step in the workflow definition. There are various types of work item. Work Item Container Runtime representation of the task container. The work item container contains the actual values of the task container at runtime. Work item Text Text that describes the work item in the integrated inbox. The work item text is defined as part of the definition of the single-step task. The work item text can include up to four expressions that refer to the task container. A text is then displayed at execution time, which incorporates the current values of the container elements. Workflow Builder Modeling tool for creating a workflow definition. You can create and process workflow definitions in the Workflow Builder. The workflow definitions created can be tested and activated. You can include existing single-step tasks and multistep tasks into the workflow definition using the integrated Workflow Explorer. The workflow container can also be processed directly.

The Workflow Builder is subdivided into the following areas: The following areas are disjointed in the display: insertable step types, containers, my workflows and tasks, document templates, WorkflowWizards, and workflows ofthis definition. You have to choose one each time. Workflow Container The workflow container contains workflow-specific system elements and other container elements to be defined explicitly. Container elements for which the import or export indicator is set form the interface of the workflow. This interface is valid for all versions of the workflow definition. Container elements for which no import or export indicators are set are local container elements of the workflow definition. They are subject to versioning and are only valid in the versions of the workflow definition in which they were defined. They can be used as indicators or internal counters, amongst other things. Workflow Definition Technical description of a workflow. A workflow is defined using the Workflow Builder, and the workflow definition is always part of a multistep task. A workflow definition is made up of individual steps and events with one step and one or more events making up one unit. These units can be arranged in sequence or in parallel.

A workflow template contains: Initial values The binding identifies the relevant data required to execute the workflow. It establishes the connection between the input data required to execute a task and the output data as the result of the task, which has to be transferred to the next step in the workflow.

Workflow Log Log of a workflow, which contains all the workflow steps for which processing has been at least started so far. In a workflow log, you can double-click on work items to display them (and change them if you have the appropriate authorization). Any errors during a workflow are displayed in the workflow log and can be analyzed with the help of the error messages shown. The following information, amongst other things, can be called using the workflow log: You can call the technical workflow log (which has an extended display) from the workflow log. Workflow Task Multistep task created by a customer to meet their specific requirements. A workflow task contains a workflow definition. The following apply to workflow tasks: Workflow tasks will not be supported in the future. New workflows should be given the type workflow template. Workflow Template Multistep task with the following properties: SAP workflows are supplied as workflow templates. You can: You should assign the type workflow template to all new workflows, because workflow tasks (the alternative) will not be supported in the future. Workflow Wizard Dialog-oriented user guide that simplifies the definition of workflows in standard situations. There are wizards that just create step sequences within a workflow definition. These can be found in the Workflow Builder. Wizards that create a new workflow definition are in the Workflow Wizard Explorer. You can, however, also use these wizards in existing workflow definitions. In this case, a new workflow definition is not created. Workflow Wizard Explorer Tool in which all the available Workflow Wizards are listed with their short descriptions and documentation. You can start the Workflow Wizards from the Workflow Wizard Explorer. The Workflow Wizard Explorer can also be started from the Workflow Builder.

Workflow Work Item Work item that represents a multistep task at runtime. There is one workflow work item (type F) for every multistep task started. The history, workflow log, and workflow container of this workflow work item can be accessed: Workflow work items are not displayed in the Business Workplace, but can be found using the work item selection. If a workflow task or workflow template is referenced as an activity in a workflow definition, this task is also represented by a workflow work item. Worklist List of all work items assigned to a user at a point in time. The user is one of the recipients of each of the work items. The worklist is in the workflow inbox in the Business Workplace. NOTE

4 chapter SAP Workflow with Function Modules and Reports What do you find in this chapter? 4.1 PURPOSE The purpose of this document is to give a brief description of all the available relevant Workflow with Function Modules and Reports. 4.2 DETAILS Function Modules

1. SWIWORKITEMSOFOBJECTGET The Function Module is used to pick all the work items generated, related to specific Document Number, based on the type of Business Object and Key. The below function module is used to get all the instances based on the key values. It will also extract all the work item ID's based on Key fields.

1. SWWWIAGENTS_READ The Function Module is used to get the Agents based on the work item.

Tables: SWWWIHEAD: Workflow Runtime: Header Table for All Work Item Types. SWWUSERWI: Current work items assigned to a User. Swwloghist: workflow log history table SAP Workflow Review Checklist NOTE

5 chapter SAP Workflow Review Checklist What do you find in this chapter? 5.1 PURPOSE The purpose of this document is to give a brief description of all the available relevant Workflow QA review checkpoints, rules and guidelines and best practices. 5.2 BUSINESS OBJECT / CLASS OBJECT 5.3 TASK

5.4 WORKFLOW TEMPLATE 5.5 CONFIGURATION The following are a must in testing client: 5.6 PERFORMANCE CHECKS Inbox NOTE

6 chapter Demo - SAP Workflow for

Credit Memos What do you find in this chapter? 6.1 BUSINESS REQUIREMENT When a SAP user creates or changes a credit memo, the value of the credit memo is checked against a limit and if the user is not authorized for that limit, the user's superior is notified to approve/reject the document and the credit memo is blocked. 6.2 CREDIT MEMO WORKFLOW Designed to be switched on/ofF for a Sales org via config (flag on ZVKORG) Designed to have minimum effort in organizational setup (two org units, generic positions, users attached to positions) Designed to have minimum changes when users change (limit levels are on position not user) Designed to have minimum changes when money limits change (values for limits are on custom config table) 6.3 ORGANIZATION STRUCTURE To minimize initial effort and maintenance, only two organization units are used: Credit Memo Organization unit Credit Memo Admin unit (used as a default for notifications) They are independent of any other organization hierarchy that may be set up. The IDs of these org units are held in a custom table (ZVWFORG — keyed on Sales org and Document type) and the workflow will only look in these hierarchies. 6.4 POSITIONS The hierarchy for authorization is the position hierarchy. All positions are linked to the single Credit Memo Organization unit. The value levels are held against each position, using codes configured for the standard sap info type I 1010 ("resources/authorities"). The codes are linked to actual values via a custom config table keyed on Sales Org and document type. If the limits are to be changed, only the config table needs to change. 6.5 USERS Users (SAP user IDs) are attached to a position, and their Credit Memo limit is determined from the position. If a user is promoted, for instance, the user ID can be re-attached to the new position and will take the limit from there. 6.6 RAISING A CREDIT MEMO The credit memo workflow is triggered by: creation of a credit memo, or change of net value or billing block on the credit memo Credit memos are configured (by document type) to propose a billing block at creation time. (for the UK = 08) The workflow only acts on credit memos where the billing block is blank or 08. A credit memo with any other billing block is ignored by the workflow until the billing block is removed, at which point the workflow is activated and checks the authority. The workflow determines the authority of the user creating or changing the credit memo. If the user has authority for the value, the billing block is removed.

If the user does not have authority, the workflow goes up the position hierarchy to determine the first position superior to the user's position which does have authority for the value, and notifies all users in that position. In the case of the UK, most credit-memo raisers are in the CSC, divided into teams, and team-leaders and managers will be easily able to pick up the notifications relevant to their own staff. Also, this minimizes maintenance, because if a team-leader is on holiday, for instance, other team leaders can pick up the notifications without constantly setting up substitutions in the position hierarchy. As most of the approvers of credit memos etc. are in the CSC and in SAP all the time, most notifications will be to the SAP inbox. If required, some levels of authority can also receive notification by e-mail (flag on the value table). If a user who is not in the hierarchy raises a credit memo, or for some reason a superior position cannot be found, the workflow will notify the designated users in the Credit Memo Admin org unit. Credit memos raised by automatic processes are not subject to the workflow. To create a credit memo in DGE (these are Tom's notes) 6.7 EDITING ORGANIZATIONS / POSITIONS Transactions PPOCE, PPOME, PPOSE to create/change/display. Best to use PPOME for the demo. Find the Credit Memo Organization unit (structure search on Organization Unit, under Org. Plan for UK Gases) The two org units are UK Gases Credit/Debit Memo Workflow and UKCredit/Debit Memo WF Admin. Double click on UK Gases Credit/Debit Memo Workflow. This displays a view of the org unit on the top right of the screen. Initially you can choose the staffassignments view, (select from the list under the icon — top left of the sub-screen). To see more of this part of the screen, hide the detailed view by clicking on the icon ) (to get the detail view back, double click on UK Gases Credit/Debit Memo Workflow again) The staff assignments view shows the positions (in the order they were created) under the credit memo org unit. This demonstrates that there is no hierarchy of org units for this functionality. To see the position hierarchy, double click on the position CSC Director, then select position hierarchy from the list under the icon 6.8 SETTING THE CREDIT MEMO LEVEL ON A POSITION Double click on a position, so the detail sub screen is visible. (just highlighting the position doesn't work) Then from the top menu bar: GOTO => Detail Object => Enhanced Object Description Make sure that the active tab is on top. If Authorities/Resources already exist for the position, there will be green tick against the authorities and resources line. To display them, click on the Authorities/Resources line and then on the overview icon . (this is in case there are several authorities/resources on the position). Select a line and click on edit or display. Alternatively, click on the line and then on the usual display edit or create icons. The Credit Memo (and Debit Memo) authorities are configured subtypes of Info type 1010. 0003 is for Credit Memos, and has resources C01-C07 (value levels) assignable to it. 0004 is for a future Debit Memo workflow. To change the authority, select subtype from the drop-down list (0003 for credit memos). To change the level, select a new resource from the drop-down list and save.

Values for the Limits Sales Org, document type, subtype id (=0003) and resource id are the key values for config table ZVWFAUTHLVL which carries the actual limit value and currency. This means that one set of levels is configured and the values can vary according to Sales Org, and document type. This table also carries the email flag. The best way to create a position is to copy an existing one in the hierarchy — highlight the position to be copied and use the copy icon or copy under the right-hand mouse button. This puts the new position in the hierarchy in the same place as the copied position. Also, it keeps the "Level" of the copied position. Positions can be drag-and-dropped. 6.9 ASSIGNING USERS Users are assigned to a position. Highlight the position, and click on icon The relationship must be A 008 US Holder User. Choose that, then choose a user to assign to the position. To move a user to a different position, drag and drop — then delete the original assignment (say no to create a vacancy). Care should be taken not to put a user in more than one position in the hierarchy. NOTE

7 chapter Demo - SAP Business Workflow - Substitution What do you find in this chapter? 7.1 SUBSTITUTION You have the option of naming a substitute when you are absent. The substitute can display and process your work items for the duration of the substitution. You must define the substitute in advance. Provided the substitute is not a user who is excluded, they can display and process your work items for the duration of the substitution. The substitute does not need to be assigned as a receiver, or as a processor of the underlying task.

Substitution for Scheduled or Unscheduled Absence The rules for substitution vary depending on whether the period of absence is scheduled (for example, a holiday), or unscheduled (for example, an illness). Scheduled Absence When a period of absence is scheduled, you name a substitute and then activate the substitution (active substitution). Your work items are automatically forwarded to the substitute for the duration of the substitution. The substitute is then able to process both their own and your work items. This document describes about substitution of the workflow Task based on the Task and classes. Substitution is option provided by SAP assigning a person to act on your work items when you are in absence. This substitution can be based on the workitem Task. E.g.: ESS Workflows can be Substituted to Person A. MSS Workflows Can be substituted to Person B. Following are the steps to achieve the above type of substitution:

7.2 DEFINING SUBSTITUTION PROFILE The authorizations of a substitute are determined by the substitute profile which you assign to him/her when you set up the substitution. A substitute profile comprises specific task classes. In the below sample. I have taken two types of substitution profile one is for ESS process and another one is for MSS process.

Here two new substitution Profiles have been created ESS & MSS

7.3 DEFINING TASK CLASSES You can classify tasks and therefore group them together according to your own criteria. A task can be classified when it is defined. Tasks which already exist can also be classified later.

Three task classes created are as follows:

7.4 ASSIGNING TASK CLASSES TO SUBSTITUTION PROFILES In this step you determine which task classes are grouped together in a proxy profile.

As per the scenario Leave request will come under ESS profile and pay change and position change will come the MSS profile. Leave, pay change, position change will Assign to ALL profiles, so this task will classified for "ALL" substitution profile also.

7.5 ASSIGNING TASK CLASSES TO DIALOG TASK

Leave classification is assigned to Leave Request Approval Task Pay change is assigned to MSS Pay change Approval Task Position assigned to MSS position change approval Task Note: In case if your configuration client is different from the development client, do a client copy of the transport to your development client and do the below mentioned settings

After assigning the task classes move to the Testing client by the report RE_RHMOVE30 by creating the manual transport request. NOTE

Demo - When a FI Document is Parked then Trigger Custom Workflow 8 chapter What do you find in this chapter? Reference: Akash Gupta's Artefact 8.1 INTRODUCTION This document shows step by step process for the creation of workflow, which is triggered whenever a document is parked. Functionality for posting is also covered.

Workflow configuration needed to be done is also explained. 8.2 BUSINESS SCENARIO Initiator parks the document. Workflow is triggered on COMPLETED event. It is sent to Finance Officer. He /she either release the document for payment or reject it. Upon release document is sent to Finance Manager. That person can view it, post it or reject it. 8.3 NOTIFICATIONS When workflow is triggered, initiator receives a mail that document has been sent to his supervisor. When document is rejected, workflow is set to complete and initiator can be sent a comments mail. 8.4 BUSINESS OBJECT USED FIPP 8.5 CREATION OF WORKFLOW - STEPS Go to transaction SWDD. Create a new workflow and save it under your package.

Go to Work flow container and add a new element. The following screen opens:

Create a new element, ZFIPP as we are using BO FIPP.

Also, set import and export parameters.

Click on the Basics Data button or press Ctrl-F8 and enter the work flow starting event.

We want the work flow to start on Completed event of FIPP BO. Activate the triggering event. It will be done thru a Customizing Request.

Also, generate Automatic Binding.

Both the Activation and Binding buttons should be green by now.

Now our workflow should look like this: Event is successfully configured.

Now we want to send email to the initiator that document number xxxxx has been sent to his supervisor. Enter a mail step.

Now we want to add a task which will enable the supervisor to release amount for subsequent posting. Add a new task. We will use RELEASE method of FIPP BO.

Now our workflow looks like the following:

Now on rejection, we want to add a MAIL interface, so that supervisor can add some comments on why he is rejecting this document. We will be using standard SAP business workplace mail for this purpose. On rejection add the following task under a new activity: TS20000139.Also add a process control which will set our workflow to complete.

Now our workflow looks like this.

Also, add a mail step in rejection to send to initiator a mail that document has been rejected. Now we will come to the condition that supervisor releases the payment, we need to set a release flag. Define an element named released. Don't forget to set its import and export parameters.

Add a container operation and set the following settings:

Our workflow now looks like the following:

Now that the document is released by the Finance Officer, we will add a user decision step, for the Manager. The Manager will have the following options: Let's make a User decision.

For review add a new activity using the standard method DISPLAY of BO FIPP.

For post, add a new activity using the standard method POST of BO FIPP.

For rejection, use previous done email step and send email to initiator that the document has been rejected. (Not being shown here) The user decision step looks like the following:

We have now completed all the required Work flow tasks and steps. 8.6 FI PARKING WORKFLOW CONFIGURATION STEPS Now we need to configure our Workflow. Go to Transaction code OBWA. Create a new variant.

Go to transaction code OBWJ to assign your variant to your own company code.

Work flow configuration is now complete. We have created a new variant and registered it to our company code. Our workflow is now ready for testing.

Enter the relevant data and press the Park Button. The document will be parked.

When the USER press the SAVE AS COMPLETED button, the work flow is triggered and he receives the mail.

Finance Officer will receive the following work item.

He will have option to release or reject the document.

On reject, the following send mail screen is opened for comments purpose.

An automatic notification is also sent to initiator that the document is rejected.

If the finance officer releases the document, the document is sent to finance manager who can post it, reject it or view it.

8.7 SUMMARY This sums up our FI Document Parking workflow. We have seen the events to trigger the workflow, release it for payment, mail users, use BO FIPP methods for posting and display and seen how to configure it. NOTE

9 chapter Demo - Goods Returns Workflow What do you find in this chapter? Reference - SAP FastTrack Artefacts 9.1 GENERAL INFORMATION A workflow approval process needs to be developed to support the future returns process. This workflow is based on the dollar amount of the return and includes the following potential roles are included in attached process flow:

Workflow is event managed — requests will be sent upon saving a new document or changing an existing one. 9.2 BUSINESS NEEDS AND REQUIREMENTS Power India Limited started its operation in the year 1965. From its humble beginning in a small town of Maharashtra called Ranjangaon PIL has achieved several milestones and today it is one of the largest manufactures of storage batteries in India. Currently the company is having seven production facilities in India namely Ranjangaon, Pune, Nashik, Chennai, Hosur, Gurgaon, and Durgapur respectively. Power India Limited, the flagship company of the Oscar group is the market leader in the storage battery industry. It manufactures wide range of batteries from 2 Ah capacities to 10500 Ah to cover the broadest spectrum of applications. 9.3 ISSUES NA. 9.4 SELECTION SCREEN DETAILS NA. 9.5 CURRENT FUNCTIONALITY The current return process today is as follows: Customer service completes a return authorization (RA) in the system: Sales person routes an OAR for large return requests: No visibility (inbound receiving, customer service, inventory management, etc.. ) in system that a return is in process 9.6 DESIRED FUNCTIONALITY The proposed TOBE process is as follows: Customer service/demand chain will be responsible for entering all RAs into the system Automatic workflow for approval All RAs will be in the system and be able to be tracked (entry through return of the product) The returns workflow will be triggered when the credit/return is greater than $1000 The workflow will also be triggered for only order types ZMCR, CR, and RE using the VA01 transaction A workflow approval process needs to be developed to support the future returns process. This workflow is based on the dollar amount of the return and includes the following potential roles are included in attached process flow: Workflow is event managed — requests will be sent upon saving a new document or changing an existing one. 9.7 TECHNICAL DETAILS

Workflow will be developed in SAP using the following three tiered schedule of authority: Assumptions Analysis Needed Cost/resources needed Recommended Approach Standard SD credit workflow objects. Object Types SAP Business Workflow has been developed on an object-oriented basis. The business object types are identified and described with their object methods in the Business Object Repository (BOR) of the R/3 System. Generally one object is created in the system and then processed in a workflow over several steps by various employees. A workflow template contains: The binding identifies the relevant data required to execute the workflow. It establishes the connection between the input data required to execute a task and the output data as the result of the task, which has to be transferred to the next step in the workflow.

Overview Customer return specialists will create a return in SAP using VA01 with a dollar amount greater than 1000 and that will trigger a workflow event. The workflow that initiated with this event is WS9100003. Design Details with Pseudo-code: Workflow: Create Workflow: Workflow Container Create a container object with the Business Object BUS2102 and main that object as import, export and mandatory. Event Receivers: Create appropriate Event Receiver Function modules to create and check the starting conditions and subsequent receiver types. Routing Mechanism Create a routing mechanism to route the workflow by picking up a reading the initiator and routing to the next level using the returns workflow organization. Outputs: The desired output must follow the table mechanism. Assumptions / Notes: Reporting hierarchy will be well defined including with the workflow initiator. As of now the dollar amount is fixed inside the workflow. Anything that we have not mentioned in the fictional as well as technical specification is considered is as out of scope. Business Process Organizational view:

Business Process Organizational view:

Technical Overview Customer return specialists will create a return in sap using VA01 with a dollar amount greater than 1000 and that will trigger a workflow event. The workflow that initiated with this event is WS9100003. Design Details with Pseudo-code Workflow Create Workflow: Workflow Container: Create a container object with the Business Object BUS2102 and main that object as import, export and mandatory. Event Receivers: Create appropriate Event Receiver Function modules to create and check the starting conditions and subsequent receiver types. Routing Mechanism Create a routing mechanism to route the workflow by picking up a reading the initiator and routing to the next level using the returns workflow organization. The desired output must follow the table mechanism. Assumptions

Reporting hierarchy will be well defined including with the workflow initiator. As of now the dollar amount is fixed inside the workflow. Anything that we have not mentioned in the fictional as well as technical specification is considered is as out of scope. 9.8 STARTING CONDITIONS This report will be run on demand and once daily. 9.9 SECURITY REQUIREMENTS/ AUTHORIZATION DETAILS None 9.10 DATA MAPPING TABLES None 9.11 DESIRED REPORT DESIGN/LAYOUT None 9.12 REPORT EXAMPLE None 9.13 CUSTOM TABLES/STRUCTURE IN SAP None

9.14 RECOVERY AND RESTART If the program fails half way, it will not have any impact on any other processes or programs. It should be simply re-started by the user. 9.15 LANGUAGE OF TEXTS The texts for the report should be displayed in User's logon language. If translation is not maintained in user's logon language, he/she should be displayed with English texts.

9.16 CURRENCY AND UNITS OF MEASURE The Quantity fields should be having reference to MARA-MEINS to display the output is correct format for those fields. 9.17 ASSUMPTIONS Sales Data is accurately maintained in the system. 9.18 ERROR HANDLING Check for proper validations and error conditions. 9.19 TESTING SCENARIOS NOTE

10

chapter Demo - Workflow for MRP Purchase Requisitions What do you find in this chapter? 10.1 BUSINESS REQUIREMENT As per Standard SAP process, workflow event doesn't triggered for PR created through MRP process. Air India SAP Core team wanted to have workflow for PR created through MRP process because it is mandate for the approval process followed at Air India as a part of compliance guidelines. 10.2 SOLUTION We suggested client to create Plan order first through MRP batch job instead of purchase requisition and then convert those Planned Orders to Purchase Requisition. PR created from planned order has creation indicator "U" and workflow event triggers for it. 10.3 BUSINESS PROCESS FLOW

Planned order to PR Conversion Process Existing MRP Run process at Air India

Propsed process flow

Example: Planned order created for the material 1018415 through MD02 transaction in foreground.

Planned order 6032 created and updated in table PLAF as mentioned in the following screenshot:

Execute the custom program ZMM022 for converting Planned Order to Purchase Requisition.

There is selection mode to execute this program in foreground (A) or background (N).

After executing this program it would convert planned order to Purchase requisition as mentioned in the following screenshot:

Now Workflow Triggered for PR created in this process as shown in the following screenshot:

NOTE

11 chapter Workflow Management System Best Practices What do you find in this chapter? 11.1 INTRODUCTION In many organizations, workflow management systems are used as a backbone of their business. Workflow management systems are designed with the intention of automating the communication between different tasks (that otherwise performed manually) to produce the final outcome. At each stage (known as work step) of the workflow, an individual or group is responsible for carrying out the tasks defined in the work step. In software terminology, Workflow management systems control the automated processes (replacing the manual intervention) as well as take care

of the inter-communication between the different processes. They can be used to integrate the different software applications. 11.2 PURPOSE The purpose of this document is to describe the best practices for designing, developing and maintaining the workflow management systems. 11.3 BEST PRACTICES - GENERAL Start condition should be robust so that workflow does not trigger unnecessarily (e.g. when a conversion program is running). If the object is consistently loaded by data loading team, then a start condition should be added to check that the workflow is not getting triggered by the data load programs or being created by one of the data load team members. In case of IDOC error monitoring workflows, make sure that the workflow has a start condition on the message types for which you want to trigger the workflow. Task/container description, step name, outcome to be more meaningful and explanatory. State what check is occurring and the outcome logic Example: Check if document status is Checked. Work item texts should be maintained for the workflow and all dialog tasks with the object key as variables, so that it is easy to distinguish between the different instances from the SAP inbox or from the workflow log. Values should not be hardcoded in the workflow design instead — containers should be declared with initial values. The length of container variables to be used in Work item subject line should be short as max length of subject is only 50 char. Try to use the same container/attribute name when passing information between workflows. Containers/parameters of methods should be declared with reference to standard SAP data structure as much as possible to avoid transport errors. When a conditional check is used and there is more than one conditional output that makes sure there is a path if none of the results match. Agent determination process should be robust enough so that the workflow does not frequently go into error status when the agent was not found. The best practice is to use the organization structure to determine the agents. Since that is not always possible, the use of rules or HR roles is acceptable. Whenever possible, check that the selected agent is a possible agent before routing the workflow item to them in next step. Try not to keep the agent assignment attribute of a dialog task as General Task because if the agent determination fails at runtime then the work item will be automatically sent to the inbox of all the possible agents, which in this case is all SAP users. If agent is determined via rule, remember to check the checkbox Terminate if Rule resolution without Result so that if the Rule fails, the workflow is put into error and work item does not go to all the possible agents. Avoid inserting a background step (example Update custom Table) between the decision step and next dialog step to the same agent. Doing so, breaks the synchronous dialog chain and the user does not get the immediate popup after the completion of the first work item (only another inbox work item). Program exits may be implemented at a particular step level or at the workflow level if some processing needs to be done at predefined events during the execution life-cycle of a work item. E.g. If you want to update the date and time stamp when the work item was reserved by an agent or to update details about workflow steps in process for reporting purposes. In case of blocks with dynamic processing (ParForEach or Dynamic Sequence) always use local containers to store dynamic data (like the agents for each instance). Else if you use workflow container then the data will be overwritten for each instance and only the data of the last instance will remain. If possible, replace the events in the wait for event steps in forks with local events as they do not have any system overhead and only affect a specific workflow instance. Exceptions raised from within the workflow using local events (of type exception) or process control steps should always be contained in blocks so that a suitable exception handler branch can be defined in the block. Otherwise the entire workflow will go into error and also the workflow cannot be restarted after fixing the error. From a system performance perspective, it is always recommended to switch off the event trace in non-development systems. Even in the development system, the event trace may be configured to restrict event logging for only the business object types (or any other event or receiver criteria) relevant for you via transaction SWEM. 11.4 BEST PRACTICES FOR DESIGN AND DEVELOPMENT If a subtype is created for a business object type then delegate it before creating workflow template. Use the name of super type throughout during workflow/task definition. Never use name of subtype.

One of the best practices in BOR programming is that if the parameter to be used in a method is already available in the BOR as an attribute then use SWCGETPROPERTY macro directly. Do not create extra import parameters in the methods. If the BOR attribute or method is not dependent on the object key fields then make it as instance-independent. If a variable is evaluated within a workflow and can be changed during the workflow process a background method is the better approach otherwise use an attribute. Because of the limitations with the table control editor used in BOR programming, use custom function modules or class/methods instead of implementing the business logic in the method if the logic is large or complex. Parameters of methods should be declared with reference to standard SAP data structure as much as possible to minimize the possibility that transport errors could result due to the custom structure not being timely transported. Group together several small background methods in one large group (a work item is created for every background step). Replace asynchronous methods by synchronous methods wherever possible (to relieve the system from having to wait for the terminating event and make a tRFC call to the receiver). If SY-UNAME is required for any logic inside a background method, import it from the workflow template. SY-UNAME if used directly in a method will always have the value = WF-BATCH'. Exception in methods to be more detailed and raised at all possible levels with different error message to facilitate error tracking and restart after error options. If a business object is to be extended, a subtype is to be created and then delegate before use in task and workflow template. Exception in methods to be more detailed and raised at all possible levels with different error message to facilitate error tracking. No method should contain raise exception statement, message type statements. If task is a dialog task, check that the agent assignment is done. If task is asynchronous, check that terminating events are attached. If deadline monitoring is to be used, change the action to Model so that the outcome is visible from the template definition. If agent is determined via rule, remember to check the checkbox Terminate if Rule resolution without Result so that if the Rule fails the workflow is put into error. Do not check input data in the first workflow step but use the option to enter a check function module in transaction SWE2 or use transaction SWB_COND instead. All business object components should be in status implemented (Object should be Generated, Saved, and Implemented). For class, all methods from the IF_WORKFLOW interface are implemented and active (may be blank). If the attribute/method is not dependent on the key fields, then it is made instance independent (for business objects) or static (for classes). Custom instance attributes are created only if they are required in workitem texts or descriptions. Custom Function Module is used instead of implementing the business logic in business object method if the logic is large/complex. For business classes, the logic is modularized in private methods. "If the method is instance dependent, the attributes of the BOR are accessed using macro SWC_ GET_PROPERTY . Extra method parameters are not created. Similarly for classes, instance attributes are used as me-> instead of creating extra method parameters". If subtype of standard business object is created, then the supertype should be delegated to the subtype. The subtype name should not be directly used anywhere in the workflow or the tasks. Every dialog task have proper work item subject as well as work item description. Redundant task containers / workflow container elements are deleted. Agent assignment and classification properties of dialog tasks are saved in a customizing transport. (If transport setting is manual then the agent assignment and classification attributes may be recorded in a CTS using transaction RE_RHMOVE30).

All container element names, step names, and outcomes are elaborate and meaningful. "The variables used in work item subject line for ""Send Mail"" steps should be short as max length of mail subject is only 50 char". Start conditions for workflow are attached to the event (transaction SWB_COND) instead of checking them with a condition step inside the workflow. A background step is not inserted in between two dialog steps being sent to the same agent(s). Doing so breaks the synchronous dialog chain and the user does not get the immediate popup. All bindings between event, workflow, task, block, method and rule are checked separately for syntax errors. Event linkage is active in testing client and recorded in a Customizing Transport. Configuration for raising event via change document/status management/message control is complete. If there is a start condition then the start condition is active. For Master data workflows, a suitable start condition is attached so that the workflow is not triggered during data load activity. Rules, organization structure, supervisor relationships, distribution lists etc., related to agent determination are properly maintained in testing client. "In workflow inside workflow method, error handling can never be done using MESSAGE ID SY-MSGID etc in case if function module call fails as it will result in short dump. In case if function module call fails, it's preferred to use macro concept (ExIT_RETURN) to handle the exceptions." Generate version each time you change the template. Avoiding Infinite Loops Avoiding infinite loops in the workflow is the key factor deciding the performance and efficiency of the workflow. While designing the workflow, one should pay extra attention to the work items going through the same work steps multiple times. If that is the case, root cause must be analyzed and proper fixes should be put in place. Load Balancing of Decision making Work Steps Decision making work steps of the workflow are the key components of the workflow. They route the work item to the appropriate work steps by making the decisions based on the input parameters. The decision making work steps of the workflow should be properly balanced in terms of load. They should not be receiving inputs from too many sources; neither should they keep on flooding few particular work steps of the workflow. If a decision making work step is getting input from too many sources, classification of the sources and consequent addition of multiple decision making work step is advisable. If they need to send too many items to particular work step, it should be properly handled in such a way that it should not affect performance. Having Review Work Step Though the Workflow Management Systems are designed to automate the work, few times the manual intervention is also required. While designing the workflow, it should be considered to have a review work step which will give a chance to correct human errors if any, before the work item goes to finalization. Work Step for Manual Processing Workflow is meant for automation of the work. However, there could be some errors (due to system bugs, human error, system crash, etc.). To handle those, it should be always preferred to have few work steps which will allow manual processing of the work items. Such work steps will help in disaster recovery management and will reduce the impact on the business in case of major issues like system crash. Automated Notifications Sometimes one or more system components may stop working due to various reasons like memory leakage, some system error, hardware failure, etc. In such cases, the support and maintenance team of the system should be notified immediately. Automated notification mechanism comes to help here. Workflow Management System should be designed in such a way that when a particular work step is flooded with large number of work items or if there is no input for the workflow when it is taking input from some other system, an automated alert (e.g. an email or a incident ticket) should be triggered to the support team. This will help minimizing loss to the business. 11.5 BEST PRACTICES FOR SUPPORT AND MAINTENANCE

Reintroducing the Work item to Workflow There are many reasons for reintroducing a work item in the workflow. They include corrupted or damaged files/documents, wrong data entry for the work item which leads it to incorrect work step, human errors, system issues, etc. When a work item is re-introduced to the workflow as a new copy, the support team needs to make sure that the old one is removed from the system. Otherwise, it will create duplicates in the system and consequently, it may have direct financial impact as well. E.g. if the documents are sent to a third party vendor for further processing and the vendor charges on per document basis for processing, any wrong document send to vendor will be an unnecessary cost. Return-from-pend Deadline Many times, the work items need to be kept on pending as some inputs are required from a department internal to the organization or from some external vendor/customer. If a work item is kept in pending work step, there should be an SLA as for how much time it should remain as pending. The return-from-pend deadline is critically important as the work item will be waiting for response/input in PEND work step indefinitely and may overshoot the SLA and result into penalties. Support team should configure the workflow to take care of the return-from-pend deadline. Locking and Unlocking the Work item In Workflow Management System, many users or groups, work together on one or more sets of work items. So it is highly important to lock the work item before starting work on it and then unlocking it after the work it done. This avoids the concurrent access/updates to the work items and data inconsistency. When a support team is working on a work item for some troubleshooting, it becomes very important for them to lock and unlock the work item. If they forget to unlock it, the work item will remain locked by them and no business user can work on it. It may conflict with the work item processing SLA. 11.6 SAP BEST PRACTICES & LESSON LEARNT SAP Best Practice is to always abide by client specific naming, programming, process, documentation, methodologies guidelines and using some accelerators/tools/plans/reusable assets /SAP Learning Hub/ Practitioner Portal etc. to deliver good quality, best feasible, time and cost effective solutions to enhance customer, business and organization delight. Purpose Best Practices can help us: To have more details kindly refer to the below articulated URLs / real-time business scenarios artefacts enclosed herewith. References SAP Best Practices — http://help.sap.com/bestpractices SAP Best Practices — http://service.sap.com/bestpractices Lessons learnt from different real time business scenarios in several projects as well as from Managed Service. Ensuring adherence of SAP Best Practices and Reusability SAP ABAP Consultants are ensuring adherence of SAP Best Practices and reusability of objects abiding by the following practices: By following Quality Artefacts (ABAP Programming Standards doc, ABAP Development Naming Standards doc, Programming Methodology Checklist, QA Review Checklist) rules & guidelines. Taking help & guidance from the below articulated Portals and SAP learning hubs regarding SAP latest technologies, best practices, assets, Communication best practices and protocols etc.

ABAP QA Checklist, ABAP Programming Standards, ABAP Development Naming Standards, SAP ABAP Programming Methodologies What is ABAP QA Checklist doc? The purpose of this document is to articulate a common set of QA inspection points regarding naming and coding standards, programming procedures, processes, and technical best practice during development, and documentation of custom solutions within the SAP environment. Why ABAP QA Checklist doc is needed? It ensures consistent QA inspection points regarding naming and coding standards, programming procedures, processes, and technical best practice during development, and documentation of custom solutions within the SAP environment. What are the advantage(s) of ABAP QA Checklist doc? The objectives of this document are to maximize the quality, value and maintainability of each custom solution proposed by the Customer SAP Project. Thus, it is essential that each person performing programming activities familiarizes him/herself with, and adheres to these common set of standards. What is ABAP Programming Standards doc? The purpose of this document is to articulate a common set of standards and procedures for the development, and documentation of custom solutions within the SAP environment. Why ABAP Programming Standards doc is needed? It ensures a consistent set of programming guidelines, rules based on SAP best practices code optimization principles during development of ABAP objects. What are the advantage(s) of ABAP Programming Standards doc? The objectives of this document are to maximize the quality, value and maintainability of each custom solution proposed by the Customer SAP Project. Thus, it is essential that each person performing programming activities familiarizes him/herself with, and adheres to these common set of standards. What is ABAP Development Naming Standards doc? The purpose of this document is to articulate a common set of standards and procedures for the naming during development, and documentation of custom solutions within the SAP environment. Why ABAP Development Naming Standards doc is needed? It ensures consistent naming conventions during development of ABAP objects. What are the advantage(s) of ABAP Development Naming Standards doc? The objectives of this document are to maximize the quality, value, and maintainability of each custom solution proposed by the Customer SAP Project. Thus, it is essential that each person performing programming activities familiarizes him/herself with, and adheres to these common set of standards. What is ABAP Programming Methodology Checklist doc? The purpose of this document is to articulate a common set ofstandards and procedures for programming during development, and documentation of custom solutions within the SAP environment.

Why ABAP Programming Methodology Checklist doc is needed? It ensures consistent programming methodology during development of ABAP objects. What are the advantage(s) of ABAP Programming Methodology Checklist doc? The objectives of this document are to maximize the quality, value, and maintainability of each custom solution proposed by the Customer SAP Project. Thus, it is essential that each person performing programming activities familiarizes him/herself with, and adheres to these common set of standards. Hard Coding - Categorization & Recommendations Hard Coding — A common Issue Hard Coding refers to the software development practice of embedding input or configuration data or even transaction data directly into the source code of a program, instead of determining that data programmatically using logic or retrieving the data from configuration/tables in single or multiple steps. Why it is Strongly Recommended to Avoid Hard Coding It is strongly recommended to avoid hard coding at company code level as it is coming under High severity defect category. If Business variables are hard coded using literals or constants, then it limits the extendibility of the program to newer scenarios. Hard coding of System variables and File path/File directory makes the program rigid and increases the maintenance overhead of the program. Hard coding means the coding practice to specify a data value within a code, which restricts the program execution for that specific data only. As per IBM development standards, NO such hard coding should be done in any development, NO Hard Coded Literals/Constants should be present in the Code for those. The strategy for handling constants can vary between projects, but it is always recommended to follow the below articulated SAP Best practices which provide maximum scalability / flexibility. For example: Use TVARVC table / Project-Specific Constant Table for maintaining constant values Make it a part of Selection Screen, derive the values from Program Selection-Screen Develop a dynamic logic in program using Function modules, tables, methods, ABAPTRUE, ABAPFALSE etc. as per current business requirement(s) Use Text id(s) for program output texts and literals with translation purpose Classification of hardcoding: High Impact/Severity: Literals or Constants used for 1) Business variables like Organization Structure/Element, G/L account, Sales org, Chart of Accounts, Company Code ,Customer number, Vendor number, Create/Change/Display T-Codes (especially for enhancements) 2) System Parameters like system id, current date, current time etc., 3) File path/File directory 4) Hard coded User Id Checks, Hard Coding in forms/reading texts, Hard coded form name in driver program in the code etc. Medium Impact/Severity: Literals or Constants used for specific values of fields (e.g. Document Type, Movement Type, Order Type, Item Category etc.) and these constants are used at different places in the code. Low Impact/Severity: Hard-coded literals used in code like flag, GUI-STATUS, return codes, transaction codes etc. Commonly Occurring issues in SAP Best Practices and Mitigation Plan(s) For amount values, the number of decimal places should follow the corresponding currency code configuration (Table: TCURX). Best Practice Using WRITE statement, don't use MOVE statement. Wrong → Write lvcurr to l_vcurrout currency 'JPY'. Correct → Write lvcurr to lvcurrout currency lvcurrency where lv_currency is the currency key for lvcurr and getting derived using dynamic logic. QA checklist point — For system parameters like System-ID / RFC-destination / Language / Transaction-codes etc. are hard coded — It's wrong, the values need to be derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic — NO Hard Coded Literals/Constants must be present in Code for those.

Best Practice Use CALL FUNCTION 'OWNLOGICALSYSTEM_GET' Based on project strategy RFC Destinations can be dynamically generated in code, or using the values from system tables like RFCDES, or by maintaining them in custom tables /TVARVC. QA checklist point — File name and path are hard coded — It's wrong, the values need to be derived from Logical File / Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic — NO Hard Coded Literals/Constants must be present in Code for those. Best Practice No hard coding should be done in the program for the same. Logical file names should be used instead and should be declared as parameters with default value. Use CALL FUNCTION FILENAMEGET or for application server directory browser FM or Method to get it dynamically based on user requirement. QA checklist point: Fixed values, used internally in the program (e.g. flags, table name/field name in ALV field catalog population, justification in ALV etc.) are not used as hard coded literals. Instead constants are used for them. Best Practice Kindly refer to the enclosed Code snippet: Field catalog example code guideline(s):

QA checklist point: For program output texts and literals with translation requirements, text id(s) need to be used instead of hard coded literals/constants. QA checklist point: All SY-UNAME checks and hard coded SAP user-id's / user groups, breakpoints need to be removed. QA checklist point: Generated function module name for SMARTFORMS is not hard coded in the driver program. Instead, it is derived by calling function module SSFFUNCTION MODULENAME. Similarly, for ADOBE Forms, generated function module name is derived using FPFUNCTIONMODULENAME. QA checklist point: For CALL-TRANSACTION, mode needs to be passed as a variable and not as a Constant/hard-code.

QA checklist point: For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic — NO Hard Coded Literals/Constants are present in Code for those. QA checklist point: Recommendation is to use ABAPTRUE rather than hard coded lc_x /cx/ 'X'. Similarly, use ABAPFALSE rather than hard coded space, wherever applicable. QA checklist point: No Hardcoding should be present in LSMW coding, wherever applicable. Change/Modify the LSMW structure, make necessary corrections at the relevant steps and try to retrieve this value from the Flat file itself. QA checklist point: Values are not hardcoded in the workflow design instead — containers are declared with initial values. QA checklist point: No hard coded tax procedure, tax code, account key should be present in code. You may use FM(s), table(s) to derive it. Best Practice VAT project FMs and Z tables Please refer to enclosed code snippet example: System Wxx (320) Z-table created ZWXXFTAXCODES

The table entries look like the following:

One specific entry maintained as follows:

Function Group: ZWXXFTAXCODE_MAPPING

To remove hard coded tax code,the FM has been called inside another custom FM ZWXXFEB_ DETERMINE_TAXCODE as follows:

Similar, example is found to determine tax procedure.

Commonly Observed issues Hard coding GL Account/Movement Type/Document Type in Program (e.g. Interface structure or org unit, master /transaction/config data) Wrong → "IF -lgnum EQ 203." Warehouse Number / Warehouse Complex hardcoded to 203. Correct → Use TVARVC/Sel-Screen/dynamic logic etc. in consultation with Functional Consultant and must be mentioned in both FS and TS. Selection from text tables with language hard coded (e.g. Where SPRAS = 'E', TDSPRAS in FM READ_TEXT = 'EN' etc. ), use sy-langu or NASTSPRAS dynamic logic to derive it based on business requirement. P.S — Language shouldn't be sy-langu for most of the cases rather it would be nast-langu / recipient's language depending upon functional requirement as well Wrong) → For all form calls printer name is hard coded (TDDEST = 'LOCL' etc.) Condition type hard coded in VOFM routine, Forms. Wrong IF KSCHL = 'ZABC' Correct → Use TVARVC/Sel-Screen/dynamic logic etc. in consultation with Functional Consultant and must be mentioned in both Functional Specification and Technical Specification. Commonly Observed Issues Partner Functions hard coded Wrong — IF PARVW = 'SP' Correct → Use TVARVC/Sel-Screen/dynamic logic etc in consultation with Functional Consultant and must be mentioned in both FS and TS In enhancements Hard coded TCode checks (e.g. ME22N) to trap transaction modes (create/ Change etc). Wrong → If sy-tcode = 'ME22N' Correct → Iftrtyp = lctrmodeh (Create), lc_trmodev. (Change), lctrmodea (Display), accordingly.

OR Use TVARVC/Sel-Screen/dynamic logic etc., in consultation with Functional Consultant and must be mentioned in both Functional Specification and Technical Specification. Commonly Observed issues Issues with Hard coding in manual File path Case 1 — Cross check whether all the characters in manual File path is correct or not in each box / landscape(s) like ACD, ACQ, ACP w.r.t current business requirement of CRF/SR. EX- SRQ03424579 — Looking at the FILE in ACQ for ZFINEFT_1687, the path is hardcoded as \eBankingDev.au.pmi\NABSendDev$\Domestic\1687\ It needs to be in ACP as per below code snippet, but DEV$ is hardcoded, so it causes the problem. \eBanking.au.pmi\NABSend$\Domestic\1687\ Case 2: Please suggest putting SYSID variable rather than putting ACD etc., or try to retrieve it dynamically from Report Selection Screen.

Golden Rules Code snippet Example: CASE 1: Maintain selection screen select-option values or set of constant values Go to Transaction STVARV.

Click on Change button. Please check the below checkbox.

Go to Selection Options tab and Click on Create. Give a meaningful name according to project naming standard.

Enter the group of TCODE values, which we need to, validate for a requirement inside the Enhancement. Maintain the entries.

Now SAVE the Variant Name.

CASE 2: Maintain selection screen Parameter value. example. Current month constant value say '10' The entry will look like following, in TVARVC entry, and then we can fetch the values as explained earlier in the program.

Quiz sessions on Real Time Business Scenarios on Best Practices with Possible Solutions Q1. We need to print date 10/02/2012 in Europe and in US. Developer has written as CODE SNIPPET IF gremdate IS NOT INITIAL. WRITE gremdate TO lv_rdate MM/DD/YYYY.

ENDIF. SPLIT pidate AT '/' INTO lvyear lvmonth lvdate. Is it correct? If not, what will be your strategies &/or code to implement it. Q2. Requirement: Update the Sales order billing block for Credit memo request, debit memo request and return orders through user exits. CODE SNIPPET

Is it correct? If not, what will be your strategies &/or code to implement it. Q3. lv_logsys = 'D03CLNT100'. Is it correct? If not, what will be your strategies &/or code to implement it. Q4. Requirement: Enable/disable a particular feature based on the sales organization and document type.

Is it correct? If not, what will be your strategies &/or code to implement it. Q5. In VOFM routine, Forms developer has written as IF KSCHL = 'ZABC'. Is it correct? If not, what will be your strategies &/or code to implement it. Q6 .Developer has written Partner Functions as IF PARVW = 'SP'. Is it correct? If not, what will be your strategies &/or code to implement it. Q7. Developer has written Currency Format as Write lvcurr to lvcurr_out currency 'JPY'. Is it correct? If not, what will be your strategies &/or code to implement it. Q8. Developer has written in his / her code in SELECT query as Where SPRAS = 'E', TDSPRAS in FM READ_TEXT = 'EN'. Is it correct? If not, what will be your strategies &/or code to implement it. Q9. Developer has written in his / her code printer name as

TDDEST = 'LOCL'. Is it correct? If not, what will be your strategies &/or code to implement it. Q10. Developer has written in enhancement /user exit TCode check as "If sy-tcode = 'ME21N'." Is it correct? If not, what will be your strategies &/or code to implement it. Q11. Developer has written batch split item number as '900001' in case of retrieving batch split data. Is it correct? If not, what will be your strategies &/or code to implement it. Q12. Developer has written the following File name and path as constant(s) in his code in an Interface.

Is it correct? If not, what will be your strategies &/or code to implement it. Q13. Developer has written in smartforms break vkaundil for debugging purposes. Is it correct? If not, what will be your strategies &/or code to implement it. Q14. Developer has written hard coded tax procedure, tax code, account key in his code. Is it correct? If not, what will be your strategies &/or code to implement it. Q15. Developer has written "If C_FLAG = 'X'" in his / her code several times. Is it correct? If not, what will be your strategies &/or code to implement it. Q16. Developer has written material number as constant inside FORM and during calling the form. Is it correct? If not, what will be your strategies &/or code to implement it. Q17. Developer has written company code, customer number as constants in WHERE clause in SELECT query. Is it correct? If not, what will be your strategies &/or code to implement it. Q18. Developer has written Document Type, Movement Type, Order Type, Item Category as constants in WHERE clause in SELECT query in his / her code. Is it correct? If not, what will be your strategies &/or code to implement it. Q19. Developer has written the following code snippet. Is it correct? If not, what will be your strategies &/or code to implement it. SELECT kunnr parvw expnr inpnr INTO TABLE i_edpar FROM edpar FOR ALL ENTRIES IN iexpnr WHERE kunnr = CEDI820 AND parvw = CRG AND expnr = iexpnr-expnr. Q20. Requirement: Enhancement code should work only for Return deliveries (Delivery Document type ZLR).Developer has written the following code snippet. Is it correct? If not, what will be your strategies &/or code to implement it.

Q21. Developer has written below. Is it correct? If not, what will be your strategies &/or code to implement it. fieldcatalog-seltext_m = text-023 Q22. Developer has written the following code snippet. Is it correct? If not, what will be your strategies &/or code to implement it. fieldcatalog-fieldname =

'CHARGS'.

fieldcatalog-tabname =

'IT_SUM'.

fieldcatalog-outputlen

= 2.

Q23. Developer has written C_text having value London. Is it correct? If not, what will be your strategies &/or code to implement it. Q24. Is the below code correct? If not, what will be your strategies &/or code to implement i

Q25. Call Function 'ABC' Exporting Program = 'ZABCDEFGH'. Is the above code snippet correct? If not, what will be your strategies &/or code to implement it. -----------------------------x--------------------------------Q26 Issues with Hard coding in manual File path. Case 1 : Cross check whether all the characters in manual File path is correct or not in each box / landscape(s) like ACD, ACQ, ACP w.r.t current business requirement of CRF/SR. EX- SRQ03424579 Looking at the FILE in ACQ for ZFINEFT_1687, the path is hardcoded as \eBankingDev.au.pmi\NABSendDev$\Domestic\1687\ It needs to be this in ACP but DEV$ is hardcoded so that might be the problem. \eBanking.au.pmi\NABSend$\Domestic\1687\ Case 2:

Please suggest to put SYSID variable rather than putting ACD etc. or try to retrieve it dynamically from Report Selection Screen. Answers Q1. a. CALL FUNCTION 'CONVERTDATETO_EXTERNAL' // dynamic date format b. Display format for date values are not hard coded — they are derived from user settings or country/any other business unit specific settings. c. Using WRITE statement also you can achieve user format, don't use MOVE statement. Q2. a. For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic — NO Hard Coded Literals/Constants are present in Code for those. b. Good Practice: Hard code the SD document category (VBAK-VBTYP) which is the standard SAP configuration level data. This will cover all the custom document types which ever will be created in future as well. OR maintain SD document category (VBAK-VBTYP) in TVARVC Table.

Sample code for good practice.

We can also get the document type field data from the configuration table TVAK if required (Transaction code VOV8).

Q3. Use TVARVC/Selection-Screen/dynamic logic etc. in consultation with Functional Consultant and must be mentioned in both FS and TS. For logical System name, retrieve from T000 or use FM OWNLOGICALSYSTEM_GET. Q4. Good practice: Maintain a custom table with Sales organization and document types as primary key with separate flags as follows. So that we can extend the required feature to other sales organization and document types in future. Or enable/disable whenever required. For specific Transaction Codes, maintain TVARVC.

OR For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table /

Project-Specific Constant Table / any other dynamic logic -NO Hard Coded Literals/Constants are present in Code for those. Q5. Use TVARVC/Selection-Screen/dynamic logic etc. in consultation with Functional Consultant and must be mentioned in both FS and TS. Q6. Use TVARVC/Selection-Screen/dynamic logic etc. in consultation with Functional Consultant and must be mentioned in both FS and TS. Q7. Write lvcurr to lvcurrout currency lvcurrency where lvcurrency is the currency key for lvcurr. Currency/quantity formats are not hard coded - they are derived from user settings or country/any other business unit specific settings. For amount values, the number of decimal places should follow the corresponding currency code configuration (Table: TCURX). Or From Selection Screen. Q8. Retrieve language using business logic or from logon language unless stated explicitly in the FS. If so use a retrieval logic using TVARVC/Selection-Screen / Table(s) etc. in consultation with Functional Consultant and must be mentioned in both FS and TS. Q9. Printer name should ideally be never hardcoded. Even if there is any specific business need, then apply a dynamic method like Selectionsceen/ TVARVC / Config etc. Q10. For specific TCode, use TVARVC table. For set of Transaction Codes of similar type, use — If trtyp = lctrmodea , lctrmodeh, lctrmodev or use local constant if no way exists. Q11. Use fields provided in tables to indicate higher level item to indicate batch split and other such scenarios. In case it is absolutely necessary and explicitly stated in the FS, use TVARVC/constant in this case. Q12. File name and path are derived from Logical File / Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic — NO Hard Coded Literals/Constants are present in Code for those. Q13. Goto TCode smartforms. Give the smartforms name and click on Test (F8). Click Display. From menu Option Goto -- Main Program. Now goto 3rd Form or subroutine include and put your dynamic breakpoint there. Now execute your Transaction code, say, VF02. It will stop at that particular point and will start the debugger screen. Q14. No hard coded tax procedure, tax code, account key should present in code. You may use FM(s), table(s) to derive it. Or from selection screen. Q15. Recommendation is to use ABAPTRUE rather than hard coded lcx/cx/'X'. Q16. For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic — NO Hard Coded Literals/Constants are present in Code for those. Q17. For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic: NO Hard Coded Literals/Constants are present in Code for those. Q18. For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic: NO Hard Coded Literals/Constants are present in Code for those. Q19. For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen / TVARVC Table / Project-Specific Constant Table / any other dynamic logic: NO Hard Coded Literals/Constants are present in Code for those. Q20. Good practice: Hard code the required delivery document category LIKP-VBTYP which has been updated from the configuration table. Return delivery document category = 'T'

Normal delivery document category = 'J' etc.,

For all value-based restrictions (i.e. specific fixed values) in business-logic, the values are derived from Selection-Screen/TVARVC Table/ProjectSpecific Constant Table/any other dynamic logic — NO Hard Coded Literals/Constants are present in Code for those. Q21. For program output texts and literals with translation requirements, text ID(s) are used instead of hard coded literals/constants. Q22. Fixed values, used internally in the program (e.g., flags, table name/field name in ALV field catalog population, justification in ALV etc.) are not used as hard coded literals. Instead constants are used for them. Q23. For program output texts and literals with translation requirements, text ID(s) are used instead of hard coded literals/constants. Q24. It cannot be used as hard coded literals. Instead constants are used for them. Q25. Call Function 'ABC' Exporting Program = lc_prog. Or using system variable sy-repid. P.S-

DATA: v_logsys TYPE logsys, CALL FUNCTION 'OWNLOGICALSYSTEM_GET' IMPORTING ownlogicalsystem = v_logsys EXCEPTIONS ownlogicalsystemnotdefined = 1 OTHERS = 2. IF sy-subrc 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy- msgv1 sy- msgv2 sy- msgv3 sy- msgv4. ENDIF. Issues due to upgrade (EHP7 / EHP4) Problem Statement Some objects during execution in LA/WE/EE Quality box are giving short dumps although testing was successful in LA/WE/EE Development box for all test scenario(s). Identifying Root cause(s) There is a difference between LA/WE/EE Development box and LA/WE/EE Quality box w.r.t Enhancement Pack(s) due to upgrade (EHP7/EHP4). I have identified the root cause(s) by arranging Brainstorming session(s) within team(s) and using statistical techniques (like, Fishbone diagram, Cause & Effect Matrix). Mitigation Plan(s) We have analysed each issue after seeing short dump/runtime error description ofthat particular exception(s)/ issue(s) and did version comparison of the relevant object(s) between LA/WE/EE Development box and LA/WE/EE Quality box to find out the discrepancies, implemented corrective & preventive actions in order to mitigate/nullify that specific issue/exception in the relevant box(s)/ landscape(s). Business scenario 1 & Mitigation Plan as Best Practice Problem statement 1: Keyword FETCH NEXT CURSOR works differently in EHP7 upgrade and FETCH NEXT CURSOR INTO TABLE is giving short dump in WE/EE Quality Box (WCQ/ECQ) although testing was successful in WE/EE Development Box (WCD/ECD) for all test scenario(s). Identifying Root cause(s) Keyword FETCH NEXT CURSOR works differently in EHP7 upgrade and FETCH NEXT CURSOR INTO TABLE is giving short dump in WE/EE Quality Box (WCQ/ECQ) since there is a difference between WE/EE Development box (WCD/ECD) and WE/EE Quality box (WCQ/ECQ) w.r.t Enhancement Pack(s) due to upgrade (EHP7/EHP4). Recommendation is, INTO TABLE has been changed to APPENDING TABLE to retain the functionality as depicted in the following code snippet. We have analysed the issue after seeing short dump/runtime error description of that particular exception(s)/issue(s) and did version comparison of the relevant object(s) between Development Box(s) & Quality Box(s) to find out the discrepancies implemented corrective & preventive actions (as articulated below) in order to mitigate / nullify that specific issue / exception in the relevant box(s) / landscape(s).

Mitigation Plan(s) Issues detected during Peer code review mitigated in development box itself before moving to Quality box. Cascaded the important message(s) to all TLs, PLs, team members in PMI all landscape(s) for all Projects as well as for Managed Service. Business Scenario 2 & Mitigation Plan as Best Practice Problem Statement 2: Objects containing SYST_INDEX is giving short dump in LA Quality Box (LCQ) although testing was successful in LA Development Box (LCD) for all test scenario(s). Identifying Root cause(s) Short dump happened in LCQ as SYSTINDEX (introduced in LCD during EHP7 upgrade) is missing in LCQ (as this is still EHP4). Recommendation, is to use a different variable with INT4 domain (may be COMTCFGD_ID) as depicted in the following Code snippet. We have analysed the issue after seeing short dump / runtime error description of that particular exception(s) / issue(s) and did version comparison of the relevant object(s) between Development Box(s) & Quality Box(s) to find out the discrepancies ,implemented corrective & preventive actions (as articulated below) in order to mitigate / nullify that specific issue / exception in the relevant box(s) / landscape(s).

Mitigation Plan(s) Issues detected during peer code review mitigated in the development box itself before moving to Quality box. Cascaded the important message(s) to all TLs, PLs, team members in PMI all landscape(s) for all Projects as well as for Managed Service. Business Scenario 3 & Mitigation Plan as Best Practice

Problem Statement 3: Short Dump is coming on LCD382 when executing the report ZWXXFTO030001 for IDOC monitoring (imported from WE*) as depicted in the following Code snippet.

Identifying Root cause(s) The resolution step is, we need to write the select query to DTINT2 read as well when reading SDATA because SDATA has LCHR data type as depicted in the following Code snippet. We have analysed the issue after seeing short dump / runtime error description of that particular exception(s) / issue(s) and did version comparison of the relevant object(s) between Development Box(s) & Quality Box(s) and pointed out the discrepancies ,implemented corrective & preventive actions (as articulated below) in order to mitigate / nullify that specific issue / exception in the relevant box(s) / landscape(s).

Mitigation Plan(s) Issues detected during Peer code review mitigated in development box itself before moving to Quality box. Cascaded the important message(s) to all TLs, PLs, team members in PMI all landscape(s) for all Projects as well as for Managed Service. Miscellaneous Business scenarios & mitigation plan(s) as Best Practice Problem statement 4 of miscellaneous business scenarios: Objects containing below articulated ABAP statements are giving short dump in LA Quality Box (LCQ) although testing was successful in LA Development Box (LCD) for all test scenario(s). Identifying Root cause(s)

Note: We should not use the below articulated ABAP statements in our programs until the EHP is implemented in LCP. They are not compatible with EHP4, therefore if we use them it will either fail on import or the program will ABEND. We have analysed the issue after seeing short dump / runtime error description of that particular exception(s) / issue(s) and did version comparison of the relevant object(s) between Development Box(s) & Quality Box(s) to find out the discrepancies implemented corrective & preventive actions (as articulated below) in order to mitigate / nullify that specific issue / exception in the relevant box(s) / landscape(s).

Mitigation Plan(s) Issues detected during Peer code review mitigated in development box itself before moving to Quality box. Cascaded the important message(s) to all TLs, PLs, team members in PMI all landscape(s) for all Projects as well as for Managed Service. Golden Rules for QA Reviewers before signing off any QA Review Problem statement for QA Reviewers while doing QA Review sign off of miscellaneous business scenarios containing several issues due to upgrade (EHP7/EHP4) in different Box(s) / Landscape(s): Objects containing erroneous ABAP statements can give short dump in LA/WE/EE Quality Box (LCQ/WCQ/ECQ) although testing was successful in LA /WE/EE Development Box (LCD/WCD/ ECD) for all test scenario(s). So, it is not possible for them to quickly detected all erroneous ABAP statements in a huge source code at the very last moment in a haste. Identifying Root cause(s) I have identified the root cause(s) by arranging Brainstorming session with team(s) and using Statistical techniques (like, Fishbone diagrams, Cause & effect Matrix). Golden Rules for QA Reviewers before signing off any QA Review While you will be signing off any QA Reviews, then as QA Reviewer, kindly update Charm general note with the following comments along with the QA closure comments. "Hi, I have closed this QA review for CHARM . Note: Since there is a difference between Development box (say, LCD) and Quality box (say, LCQ) w.r.t Enhancement Pack, I would suggest you to check the transport log and to do a Syntax Check in Quality box/environment (say, LCQ) once the associated TR (Say,, LCDK9C01NR) moves to Quality box ( say, LCQ)." Quiz Session Questions Answers Golden Rules in Performance Enhancement Which issues generally developers overlook or miss from performance optimization point of view? Golden Rules Any program considered for performance improvement should pass through stress testing like executing report before and after code changes to check for improvement using Transaction SE30 / ST05 / ST12 / SAT in QA box from Customer / Vendor side before assigning it to UAT, as applicable. During UAT of performance changes, volume of data should also be considered.

Use Parallel Cursor technique in case of Nested Loop. Binary Search is used when parallel cursor is not feasible and the number of entries in the internal table is greater than 20. Before using Select for all entries we need to check whether Driver internal table is empty or not. After using one Select statement check sy-subrc value. If sy-subrc is 0, then only use next select statement. During using Select for all entries use all the Primary key fields in the Select statement in WHERE clause in order to retrieve all records and to remove adjacent duplicates. For selecting single row from a database table, use "SELECT SINGLE" instead of "SELECT *" if the full primary key is known. Otherwise, use "UP to 1 Rows". The sequence of fields selected in the Select query should be in the same sequential order as per the fields situating in the corresponding database table. Avoid nested select statements. Use Inner Join and/or For all Entries / View instead. When creating joins over database tables there should be an index at least on the inner table for the fields in the join condition. Else, go for Forall-entries. Do not use Select statements inside the loop. Do not use SORT statements inside the loop. Use all key fields in where conditions during using SELECT QUERY. In SELECT statement, only the fields which are needed are selected in the order that they reside on the database, avoid usage of "SELECT *" statement. Use Select into table rather than Select into corresponding fields. Suppose, I have a huge table containing many records. During running I am getting Short Dump telling records out of page area or Time Out error. BIFRSQLINVALID_REQUEST. How to solve this performance issue? We need to use Package size in the SELECT query. Using Package size we can restrict the data flow so that at a particular time, certain number of records can be retrieved and so on. For efficiency, always do the inserts in key sequence order. SAP Performance Enhancement additional Tips & Tricks The package size you should use depends on the structure size of the table you are inserting and the size of the rollback area. Your DBAs should be able to help you in this. You cannot simply restart this program if it fails. You either have to empty the z table first or skip the records you have already inserted. NOTE: a. Internal tables are freed when no longer needed (either by the free command or a subroutine exit), especially when the tables are large or the program is a batch program. If Internal table is used again, then don't use FREE ixxx. Instead here use CLEAR ixxx. Select into table is used instead of select append and then endselect. Check whether the tables used or accessed require indices. Table access sequence optimised with buffer internal tables or table access sequence structure. Filter checks should be provided early in the code. Avoid SELECT.ORDER BY. Preferred to put the records into an internal table and then perform a SORT. Fields specified in the WHERE condition with the critical operators NOT and (negative SQL statements) cannot be used for a search using database indexes. Whenever possible formulate SQL statements positively. Make sure the first field (s) of the WHERE clause are stated with EQ.

Do not define Internal Table with "OCCURS" option. Do not use Table with Header Line. Use work area or Field-Symbols to transfer data from/to internal tables. LOOP AT ITAB WHERE K = 'XXX' should be used instead of LOOP AT ITAB / CHECK ITAB-K = 'XXX'. CASE statement preferred to multiple ELSEIFs. When using the AND or OR operator, the most likely elimination criteria is specified first. When COLLECT semantics are needed, the COLLECT command is used. For internal tables: Top Tip for SELECT ORDER BY

Top Tip for SELECT DISTINCT

Top Tip for PARALLEL CURSOR Technique

Top tip for OPEN CURSOR technique If you are inserting a lot of records from a single database table (and it seems like it here, say 2 lac), you will be in danger of exceeding the rollback area. The way around this is to insert a number of records at a time and then do an explicit commit. That's why here use of OPEN CURSOR technique is recommended. Here loop iteration happens in Variable level only, not at database level. data: g_cursor type cursor. Select Insurance Objects from ZEPCIOCONTRACT table OPEN CURSOR WITH HOLD g_cursor FOR SELECT insobject FROM zepciocontract WHERE insobject IN s_insobject AND zreltype IN szrel_type AND zcontrcode IN szcontr_code. DO. FETCH NEXT CURSOR g_cursor INTO TABLE t_ins1 PACKAGE SIZE 10,000. IF syst-subrc 0. CLOSE CURSOR g_cursor. exit. ELSE. exit. ENDIF. ENDDO. Top Tip for PACKAGE SIZE Technique in SELECT Query If you are inserting a lot of records from two database tables (and it seems like it here, say 2 lac), you will be in danger of exceeding the rollback area. Here, recommendation is to use PACKAGE SIZE technique while using Inner join. Generally it works like this:

SELECT cdhdr~objectclas cdhdr~objectid cdhdr~changenr cdhdr~username cdhdr~udate cdhdr~utime cdhdr~change_ind cdhdr~tcode FROM cdhdr INNER JOIN mara ON cdhdr~objectid = mara~matnr APPENDING table ichhead PACKAGE SIZE 10000 WHERE cdhdr~objectclas = c_mat AND cdhdr~objectid IN s_matnr AND cdhdr~username IN s_aenam AND cdhdr~udate IN s_laeda AND mara~ismhierarchlevl NE c_t. Process the 10000 records here Processing is done package by package each has 10000 rows ENDSELECT. Use of BYPASSING BUFFER addition in SELECT query - Is it preferred to use Challenge When we are retrieving data from SAP buffered table(s), then we are getting CI error. In order to nullify it often we are using BYPASSING BUFFER addition in SELECT query. But is it worth using it. ■ Ans: No. It's preferred to avoid BYPASSING BUFFER in order to minimize the database load. SELECT /bic/zchmarket FROM /bic/szchmarket BYPASSING BUFFER INTO TABLE litmarket WHERE /bic/zchmarket IN fpsodm[]. This BYPASSING BUFFER addition causes the SELECT statement to avoid the SAP buffering and is used to read directly from the database and not from the buffer on the application server. When you use the select statement for the first time, it retrieves the data from the database table and places it in buffer so that subsequent select statements for that table retrieves data from the buffer on the application server and not the database table directly, thereby reducing database load on the traffic. Use of CLIENT SPECIFIED addition in SELECT Query Challenge

When we are retrieving data, sometimes we are using CLIENT SPECIFIED addition in SELECT query. But is it worth using it. Ans: No It's preferred to avoid CLIENT SPECIFIED in order to minimize the database load. SELECT SINGLE rbstat INTO l_status FROM rbkp CLIENT SPECIFIED WHERE mandt = sy-mandt AND belnr = object-key-invoicedocnumber AND gjahr = object-key-fiscalyear. In SELECT query CLIENT SPECIFIED is used to disable/avoid automatic client handling. It is better to avoid in terms of performance enhancing standpoint. Generally, in customer system we have only one business client, Open SQL commands by default are done for the current logon client only, so we have to remove this CLIENT SPECIFIED clause for performance issues. Important points regarding binary search use in READ Challenge When we are READING data of internal table, sometimes we are skipping some basic prerequisites which in turns lead to performance issue, even short dump. Solution It's preferred to use binary search in Standard internal table if that internal table contains large volume of data. Before using binary search, always sort that internal table with the same key used in the corresponding READ statement wherever applicable. READ TABLE litmcha INTO lwamcha WITH KEY matnr = -matnr werks = -werks BINARY SEARCH.. Note: Please don't SORT within loop, Sorting must be done outside the loop. You always need to SORT in ASCENDING order, if you SORT in descending order then the BINARY SEARCH addition will not work properly. If field names &/or sequence got changed in the corresponding SORT prior to using BINARY SEARCH addition in existing code, then again you need to SORT that specific internal table just outside the loop prior to using BINARY SEARCH addition in READ. You cannot use BINARY SEARCH addition in READ for SORTED and HASHED table. There use WITH TABLE KEY addition in READ statement where exactly the full key is provided. Always check sy-subrc values after using BINARY SEARCH addition in READ. Top tip for use of RANGE Table in SELECT query

Top tip for use of DELETE ADJACENT DUPLICATES from itab

Top Tip for use of WHERE clause in SELECT Query

Top Tip for use of no Single-line update in SELECT Query

Top Tip to avoid use of SELECT* in SELECT Query

Top Tip for use of Array Operations in SELECT Query

Top Tip to Avoid Nested SELECT'S

Top Tip to Restrict Select Options for User

Top Tip to use as many EQ'S as possible in SELECT Query

Top Tip to Avoid use of NOT in SELECT Query

Top Tips While Working with internal Tables

Top Tips to Avoid SELECT SINGLE within LOOP

SAP ABAP Parallel Processing of Jobs in Background Purpose

Purpose The below articulated document explains about SAP ABAP Parallel Processing of jobs and steps to implement the parallel processing in the background. Parallel processing technique is used when we need to handle large amount of data and data is segregated in small packets and for each packet, selection is done separately. However, sometimes even using this method, it takes long amount of time and face performance issue. To overcome this issue, we can run these jobs in background, which will help us in improving the performance further. This document explains the process of how we run the parallel pockets of jobs in background. Introduction This document explains about SAP ABAP Parallel Processing of jobs and steps to implement the parallel processing in the background. Parallel processing technique is used when we need to handle large amount of data, also data is segregated in small packets and for each packet, selection is done separately. However, sometimes even using this method, it takes large amount of time and face performance issue. To overcome this issue, we can run these jobs in background, which will help us in improving the performance further. This document explains the process of how we run the parallel pockets of jobs in background. Steps to Implement Parallel Processing in Background Step1: Segregate the data into small packets

Step2: Send segregated data to method which is meant for job scheduling

Step3: Create method PROCESSBACKGROUNDJOB for creation of JOB

Step4: Receiving results of background job

Step5: Create method RECEIVEBACKGROUNDJOB_RESULT

And this table ET_MSEG is the table which we get as an importing parameter of this method, so we get all the data here. Step6: Create report which consist of select statement

Testing Best Practices in OOPS ABAP Static Methods /Attributes should not be used, unless there is a specific need. Visibility of Methods / Attributes should be properly chosen: 'Public'; those should 'Private' / 'Protected' depending on the requirement. Exceptions should be properly handled inside the Methods; a proper custom message should be used along with those Exceptions. While creating custom classes, proper care should be taken before declaring that as 'Final' The Local classes can be used, if the scope is limited within a single program / global class only. If it has to be used in several places, then it must be declared as Global. While using Local classes in a custom program, there should be a separate INCLUDE program for IMPLEMENTATION; the DEFINITION can still be declared in the TOP INCLUDE. Explicitly use the self-reference ME while accessing any Method / Attribute of the same class, instead of just using those individually. Best Practices - Miscellaneous

Best Practices in SAP ABAP - Bypass Obsoletes (wherever relevant / applicable) Don’t use obsolete statements or obsolete variants of statements (see online help for details). Rule: Avoid using obsolete statements. URL - http://help.sap.com/abapdocu702/en/abenabapobsolete.htm Maintain hard coded constant(s) in Project-Specific Constant Table (ex,ZLARF004) / TVARVC Table as ranges / Select option rather than Parameter. Recommendation is to maintain hard coded constant values always as select option / ranges in TVARVC Table / Project-Specific Constant Table (ex,ZLARF004 table) taking into account the future maintenance purpose(s), based on business need and to avoid unnecessary reductant constants declaration in table ZLARF004 / TVARVC Table / Project-Specific Constant table(s). We don't need to insert TVARVC entries if the data elements / values / TYPE-POOLs already exist in SAP We should build the logic to extract the necessary information from SAP Recommendation is to use Project Specific Constant Table rather than maintaining TVARVC table. (Ex - Project Specific Constant Table ZLARF004 in LA landscape). Form names should always be picked up from config tables (e.g. TNAPR for SD forms). For condition types/document types use TVARVC or client specific variant table heavily. For hardcoded subroutine for external programs calls always use IF Found. Never hardcode basic transaction data like customer/vendor within program. For alv calls, use sy-repid, do not hardcode the program name and same for sub screen. End Date in HR Programs (ENDDA) should never be hardcoded as '99991231'. Selection from text tables can never be done with language hard coded (e.g. Where SPRAS = 'E', TDSPRAS in FM READ_TEXT = 'EN' etc.)Recommendation is to retrieve language using business logic or from logon language unless stated explicitly in the FS. If so use a retrieval logic using TVARVC/Selection Screen / table(s) etc. in consultation with Functional Consultant and must be mentioned in both FS and TS." Printer name should ideally be never hardcoded. Even if there is any specific business need, then apply a dynamic method like Selection screen/ TVARVC / Config etc. In workflow inside workflow method, error handling can never be done using MESSAGE ID SY-MSGID etc. in case if function module call fails as it will result in short dump. In case if function module call fails, it's preferred to use macro concept (EXIT_RETURN) to handle the exceptions. For webdynpro/forms use OTR Texts and text modules/standard texts. The R/3 System contains no secondary indexes to the most important SD transaction data tables. Instead, the R/3 System has proprietary index tables (VAKPA, VAKMA, VLKPA, VLPMA, VRKPA, VRPMA,VAPMA etc.) which allow an efficient access. The SAP Note 185530 — Performance: Customer developments in SD can be referred for further information.

Custom fields newly added in Standard table/structure must start with ZZ* taking into account future version upgradation activities by SAP, in case of newly created ZCustomAppendstructure also, Custom fields newly added must start with ZZ*. In order to view Change Log for Custom table (Ztable) using transaction SCU3, the following things need to be done: None of mini HR tables (ex, HRP1218) test data entries (created only for test purpose in development box) should go by a transport from development to production. In SORTED internal table, please use INSERT statement instead of APPEND statement. INSERT LINES OF itabl [FROM nl] [TO n2] INTO TABLE itab2. For example: INSERT LINES OF littemp INTO TABLE lit3241. P.S — APPEND statement should be avoided to add entry to a SORTED table; it will raise a non-handleable exception if the sort sequence is violated. In extreme situations when Unit Testing can not be performed in development server / box due to some unavoidable reason (ex, lack of test data), in that case the Transport Requests should be moved to Quality Server, only after email approval from the Client / affiliate /Project Management. Also, in all such cases the Technical Unit Testing (TUT) and Functional Unit Testing (FUT) must be done in the Quality Server / box first by the IBM / Vendor team. Only after the TUT and FUT are successfully completed / results are properly documented, then the Business should be requested for User Acceptance Test (UAT). In no circumstances, the code changes should be directly sent for Client Testing before IBM team has tested the same. For any INCLUDE(s) present in any object(s), always, developer(s) need to check its global impact by using Where-Used List on it. In case if global impact is there, developer(s) need to mention it under Comments column of the QA Review checklist. It's MANADATORY activity for developer(s). Recommendation is to change local variable / constant values, rather than changing Global variable / constant values, in case if it is used in many different Programs, as per current business requirement, wherever applicable. You need to SORT always in ASCENDING order, if you SORT in descending order then the BINARY SEARCH addition will not work properly. If field names &/or sequence got changed in the corresponding SORT prior to using BINARY SEARCH addition in existing code, then again you need to SORT that specific internal table just outside the loop prior to using BINARY SEARCH addition in READ. You can't use BINARY SEARCH addition in READ for SORTED, HASHED table. Use WITH TABLE KEY addition in READ where exactly the full key is provided. The syntax for defining the table key is also the same as for defining table types. In contrast to the definition of table types, an internal table as a data object cannot have a generic table key. This results in a slightly different semantics when you omit the table key specification in the DATA statement or when you do not specify the uniqueness using UNIQUE or NON-UNIQUE: If for standard tables you specify no key, the table key is automatically determined as a non-unique standard key. A key specified without explicit uniqueness is implicitly enhanced with the addition NON-UNIQUE KEY. You cannot specify addition UNIQUE KEY. For sorted tables, you must specify the key fully; both additions UNIQUE KEY or NON-UNIQUE KEY are allowed. For hashed tables, you must specify the key fully; only addition UNIQUE KEY is allowed. FYI.

Bypass Obsoletes There are several statements those are syntactically forbidden in ABAP Objects or in Unicode programs. Here we have tried to collect some of those as a ready-reference: The statement RANGES is an obsolete declaration of a range tables. The statement is now replaced by the addition TYPE or LIKE RANGE OF of the statements TYPES and DATA.

The left-hand side of the following table shows obsolete relational operations. Obsolete Statements: 'Extended Syntax Checker' (SLIN) must be used after developing any custom object, to identify all these obsolete statements. Declarative Elements The following is a list of declarative elements in the order they should appear in the ABAP program, directly after the comment box. This order is only a guideline as opposed to a standard. In each case one line must be allowed before beginning the next element and must start in the first column. An element should only be coded if it is used in the ABAP report. The order is:

Tables The TABLES key word is used to declare the SAP table header lines, which the report wishes to access globally. The declared tables must be listed aligned and one per line. The description of the declared table must be mentioned on the right side. For example: TABLES: T00l, "SAP Company Code Tables T001C, "Valid Posting Periods Global Companies CSKS. "Cost Centre Master Suggestion: Do not use TABLES statement if only SELECT-OPTIONS need to be declared. In this case declare a global variable and use that in SELECT-OPTION declaration as follows: DATA: G_BUKRS TYPE BUKRS. SELECT-OPTIONS: SBUKRS FOR GBUKRS. Type Pool, Type-Pools and Types SAP provides basic data types such as C for character, N for numeric etc. The TYPES statement is used to define user data types. The userdefined type can then be assigned to data objects, formal parameters and field symbols using the TYPE addition. The type concept makes a clear distinction between data types and data objects. Example: TYPES: T_NAME(30) TYPE C, BEGIN OF ADDRESS, SURNAME TYPE SY-UNAME, FIRSTNAME TYPE TNAME, END OF ADDRESS, ADDR_TAB TYPE STANDARD TABLE OF ADDRESS INITIAL SIZE 1, BEGIN OF ST_COMPANY, NAME TYPE NAME, ADRESSES TYPE ADDR_TAB, END OF ST_COMPANY, DATA: ADDR1 TYPE ADDRESS, T_ADDR1 TYPE STANDARD TABLE OF ADDRESS INITIAL SIZE 1, TADDR3 TYPE ADDRTAB, ADDRTABLINE TYPE LINE OF T_ADDR1. In order to define standard user types which are consistent, defined only once and are available to all ABAP programs, there is a facility to store these definitions in the ABAP Dictionary. The grouping of these user-defined types is called a type group. The Type-Pool statement is used to identify a type group. Type groups can only be maintained by using the ABAP Dictionary (transaction SE11). Only types and constants can be defined in type groups. The names of these types and constants must begin with the name of the type group and an underscore. The types of type-pool can be used in any number of ABAP programs.

Select-Options The SELECT-OPTIONS statement is used to specify the selection criteria that are to appear in the selection screen. The MEMORY ID and MATCHCODE OBJECT options should be used if user defaults and display of possible entries are required when executing the report online. Mandatory selections should be specified as OBLIGATORY. For example: DATA: G_BUKRS TYPE BUKRS, G_XBLNR TYPE XBLNR1. SELECT- OPTIONS: SCOY FOR GBUKRS MEMORY ID BUK, S_PDATE FOR BKPF-BUDAT DEFAULT SY-DATUM OBLIGATORY, SXREF FOR GXBLNR MATCHCODE OBJECT ZBKN. Parameters The PARAMETERS statement asks for user input and appears on the report selection screen. When parameters are used as flags or switches, they should be specified as CHECKBOX. LOWER CASE addition is used when the 'case' of the parameter is important (e.g., in Unix filenames). For example: PARAMETERS: PFILENAME(30) TYPE C DEFAULT '/usr/sap/temp/printout.dat' OBLIGATORY LOWER CASE, P_UPDATE AS CHECKBOX DEFAULT 'X'. Ranges RANGE is an internal table similar to a selection criterion defined using the "SELECT-OPTIONS sel FOR f." statement. It can be used when the IN operator is used with SUBMIT, CHECK, IF, WHILE or SELECT. For example: RANGES R_CUST FOR KNA1-KUNNR. (Obsolete — do not use) DATA: ICUST TYPE RANGE OF TYCUST INITIAL SIZE 0. Constants Where a constant is used frequently, it is often better to define it as a constant to make the program more readable. For one character constants it may be better not to declare them as constants, as the program is often more readable if the actual string is used. Example: CLASTDATE TYPE SY-DATUM VALUE '19991231'. Data The DATA key word is used to declare local data objects (other than SAP tables) which the report can access. It is recommended to use the keyword TYPE rather than LIKE when referring to Dictionary objects. Half line comments, as a guideline should be used if necessary to provide a description of the data object. For example: DATA: WVENDORNO(l0) TYPE C, "Supplier WPLANTCDE TYPE T001W-WERKS "Maintenance Plant

WRECCOUNT(4) TYPE N. "Record Count LIKE statements should no longer be used. In the 3.x system it was not possible to use a data element directly as a type. Via a structure or table and the field name, LIKE was used to refer to field-table name. From 4.x onwards, it is now possible to use data elements as types directly in the program. Furthermore, LIKE cannot be used in the parameter definition in forms. Example: Do not use DATA: lvbeln LIKE VBAK-VBELN. Instead use DATA: lvbeln TYPE VBELN_VA. Use text elements to define a string constant or selection text. Example: Do not use ➔ WRITE : /5 TEXT-009. Instead use ➔ WRITE : /5 'Output could not be generated'(009). This way the readability of the code will be enhanced. Structures Structures, also known as a field strings, are used to restrict excessive and confusing sub-string operations, where the sub-string is a meaningful data item. The same naming conventions as those of DATA apply. Example: Holds Date in DDMMYYYY format DATA: BEGIN OF STLONGDATE, DAY(2) TYPE N, MONTH(2) TYPE N, YEAR(4) TYPE N, END OF STLONGDATE. DEMO with some Real-time scenarios & strategies during Performance enhancement of objects. Program ZPMRREMAININGLIFEFORFLEET4 (Performance enhancement) A) Performance issue (Some areas within the source code where performance needs to be enhanced) Check Driver table lt_batchrun IS NOT INITIAL before using SELECT FOR ALL ENTRIES, currently this check is not present, also put an additional check like whenever you are using Parameter or select-option in your Select query. IF NOT p_werks IS INITIAL. SELECT * INTO TABLE lt_result FROM zzpmrdd0417db FOR ALL ENTRIES IN lt_batchrun WHERE werks = p_werks AND batchnum = ltbatchrun-batch_num. ENDIF. Remove MOVE-CORRESPONDING within loop and use the alternate correct MOVE statement for each field. LOOP AT lttmp INTO lstmp WHERE hier_lvl CP lhierlvl. "ins DR1K941890 MOVE-CORRESPONDING lstmp TO gsreport. As Full key is not mentioned in the below cases in SELECT SINGLE, so better to use SELECT UP TO 1 Rows here: SELECT SINGLE low INTO l_atnam FROM tvarvc WHERE name = 'ZRDD0147FLEETLIFE_CHAR'.

SELECT SINGLE pak_text zeieh INTO (lsreport-paktext, ls_report-mrngu) FROM mmpt WHERE warpl = ls_report-warpl. ENDIF. Remove Select * and remove INTO CORRESPONDING and check sequence of the fields in where clause. IF ls_report-stich = '4'. SELECT * INTO CORRESPONDING FIELDS OF TABLE lt_mhis FROM mhis WHERE warpl = ls_report-warpl AND adpoint = ls_report-point AND lrmdt = '00000000' AND tstat = ' '. ELSE. End ofDR1K935506 SELECT * INTO CORRESPONDING FIELDS OF TABLE lt_mhis FROM mhis WHERE warpl = ls_report-warpl AND adpoint = ls_report-point and lrmdt = '00000000' AND tstat = ' '. • Check sequence of fields in where clause. SELECT SINGLE ktexl INTO lsreport-paktext FROM t351x WHERE spras = sy-langu AND paket = l_zaehl AND strat = l_strat. Use Parallel cursor technique wherever possible for nested Loop. At the End of Selection Free all the Memory area of the Internal tables whenever required. Remove SELECT within LOOP

Remove SELECT *

Remove INTO CORRESPONDING and check fields sequence in where clause.

Remove MOVE-CORRESPONDING within loop and use the alternate correct MOVE statement for each field.

Remove NESTED SELECT.

Remove SELECT ... ENDSELECT.

Remove multiple SELECT statements within LOOP.

PERFORM called in LOOP which contains multiple SELECT, amend the statements within FORM as discussed for Select statements

Use Binary Search in READ statement always. Wherever Loop at Itab is used before that always check whether that loop is empty or not. if not i_vbrk[] is initial. All fields are required for later pricing routine select * from knvv into table i_knvv for all entries in i_vbrk where kunnr = i_vbrk-kunag and vkorg in s_vkorg and vtweg in s_vtweg. if sy-subrc eq 0. sort i_knvv by kunnr

vkorg vtweg spart. Endif. Endif. Means after Selection before using Sort itab, 1st check the sy-subrc value. If successful, then only do the sorting. Some sample Solutions of common tricky Performance issues Case 1: AVOID NESTED SELECT'S : USE FOR ALL ENTRIES Don't use the following statement: SELECT * FROM dbtable1 WHERE condition. SELECT * FROM dbtable2 WHERE field2 = dbtable1-field1. ...process ENDSELECT. ENDSELECT. Instead, use the following statement: SELECT field1 FROM dbtable1 INTO TABLE itab WHERE condition. SELECT field2 FROM dbtable2 INTO TABLE itab2 FOR ALL ENTRIES IN itab WHERE field1 = itab-field1. LOOP AT itab2. ____Process ENDLOOP Case 2: Don't use below statement SELECT * FROM SPFLI INTO WA_SPFLI. SELECT * FROM SFLIGHT

INTO WA_SFLIGHT WHERE CARRID = WA_SPFLI-CARRID AND CONNID = WA_SPFLI-CONNID. ENDSELECT. ENDSELECT. Instead, use the below Inner Join statement SELECT P~CARRID P~CONNID S~FLDATE INTO TABLE I_FLI FROM SPFLI AS P INNER JOIN SFLIGHT AS F ON P~CARRID = F~CARRID AND P~CONNID = F~CONNID. Use Parallel Cursor technique in case of Nested Loop Case 1: TOP TIP FOR NESTED LOOPS Don't use below statement LOOP AT IVBAK. LOOP AT IVBAP WHERE VBELN = IVBAK-VBELN. .. .process ENDLOOP. ENDLOOP. Instead, use the below statement SORT IVBAP BY VBELN. LOOP AT IVBAK. READ TABLE IVBAP WITH KEY VBELN = IVBAK-VBELN BINARY SEARCH TRANSPORTING NO FIELDS. CHECK SYST-SUBRC = 0. LOOP AT IVBAP FROM SY-TABIX. IF IVBAP-VBELN IVBAK-VBELN. EXIT. ENDIF. ...process

ENDLOOP. ENDLOOP. In the above case, RUN TIME REDUCTION CAN BE IN EXCESS OF 50%. TOP TIP FOR SELECT SINGLE IN A LOOP #1. Case 2: Don't use below statement SELECT VBELN KUNNR INTO TABLE IVBAK FROM VBAK UP TO 1000 ROWS. LOOP AT IVBAK. SELECT SINGLE NAME1 INTO KNA1-NAME1 FROM KNA1 WHERE KUNNR = IVBAK-KUNNR. .. process ENDLOOP. Instead, use the below statement SELECT KUNNR NAME1 FROM KNA1 INTO TABLE IKNA1 FOR ALL ENTRIES IN IVBAK WHERE KUNNR = IVBAK-KUNNR. SORT IKNA1 BY KUNNR. LOOP AT IVBAK. READ TABLE IKNA1 WITH KEY KUNNR = IVBAK-KUNNR BINARY SEARCH. ..process ENDLOOP. In the above case, run time reduction can be in excess of60%. Parallel Cursor Sample Source Code Add indication for customization requirements and source node loop at t_header. l_tabix := sy-tabix. read table titem with key ylexidvpal = theader-ylexidvpal binary search. loop at t_item from sy-tabix. if titem-ylexidvpal ne theader-ylexidvpal.

exit. endif. read table lthu with key exidv = titem-ylexidvmc binary search. check: sy-subrc eq 0. read table tyl004 with key vbeln = lthu-vbeln binary search. if sy-subrc eq 0. -Begin of insert by symmalaks on 13.12.2007 READ TABLE iptd WITH KEY vbeln = lthu-vbeln BINARY SEARCH. IF sy-subrc EQ 0. titem-dscode = i_ptd-xabln. ENDIF. -End of insert by symmalaks on 13.12.2007 t_header-custom := 'Yes'. modify theader index ltabix. modify titem. " index ltabix1. "ACT15172 continue. "ACT15172 exit. "ACT15172 endif. endloop. endloop. IF p_werks IS NOT INITIAL. *Get the batch number from control table zzpmrdd04l7ctl SELECT batchnum datecreate timecreate FROM zzpmrdd04l7ctl INTO TABLE ltbatchctl WHERE werks = p_werks. IF sy-subrc = 0. SORT ltbatchctl BY batch_num. ENDIF. ENDIF. IF lt_result IS NOT INITIAL. *Get corresponding batchnumbers according to tplnr LOOP AT ltresult INTO lsresult WHERE tplnr IN s_tplnr. lsbatchnum-batchnum = lsresult-batchnum.

APPEND lsbatchnum TO ltbatchnum. CLEAR ls_batchnum. ENDLOOP. ENDIF. Some Good practice in good coding regarding Clear and refresh during using Select query Case 1: &--------------------------------------------------------------------*& Form GETSALESORDER_HEADER. &--------------------------------------------------------------------To have the Sales Order data ---------------------------------------------------------------------- * form getsalesorder_header. if not ivbaksel[] is initial. clear i_vbak. refresh i_vbak. select vbeln auart bsark ernam audat bstnk vbtyp augru from vbak into table i_vbak for all entries in ivbaksel where vbeln eq ivbaksel-vbeln. if sy-subrc = 0. sort i_vbak by vbeln. endif. endif. endform. GETSALESORDER_HEADER. Case 2: clear *mvke.

select single matnr mvgr1 pmatn kondm from *mvke into (*mvke-matnr, *mvke-mvgr1, *mvke-pmatn, *mvke-kondm) where matnr = sfp_kit and vkorg in s_vkorg and vtweg in s_vtweg. Some Good practice in good coding regarding Clear and refresh during using Loop statement. Case 1: sort ireporttemp by vbeln ascending posnr ascending kschl ascending. delete adjacent duplicates from ireporttemp comparing vbeln posnr kschl. sort i_report by vbeln ascending posnr ascending kschl ascending. loop at ireporttemp. loop at ireport where vbeln = ireport_temp-vbeln and posnr = ireporttemp-posnr and kschl = ireporttemp-kschl. lkbetr = lkbetr + i_report-kbetr. lkwert = lkwert + i_report-kwert. clear: i_report. endloop. move-corresponding ireporttemp to i_temp. move lkbetr to itemp-kbetr. move lkwert to itemp-kwert.

append i_temp. clear: lkbetr, lkwert. clear: ireporttemp. endloop. clear i_report [] refresh i_report. Case 2: ______________________________________________________________________* Form SETUPFORPRICING *______________________________________________________________________* *______________________________________________________________________* Do preliminary reads and populate structures used by pricing ______________________________________________________________________* --> sfp_kit Header material --> sfp_matnr Material --> sfp_qty Number of components required for kit ______________________________________________________________________* form setupforpricing using sfp_kit sfpmatnr sfpqty. refresh i_komv. clear i_komv. clear i_komk. clear i_komp. Retrieve master data from tables YV001 has control parameters for pricing if iyv001-werks ivbrp-werks. clear i_yv001. read table iyv001 with key werks = ivbrp-werks binary search. endif. clear i_mara. read table imara with key matnr = sfpmatnr binary search. if i_yv001-spart is initial. vnrefspart = i_mara-spart. else. vnrefspart = i_yv001-spart. endif.

clear i_marc. read table imarc with key matnr = sfpmatnr werks = i_vbrp-werks binary search. clear i_mvke. read table imvke with key matnr = sfpmatnr binary search. Get customer specific info clear i_kna. read table ikna with key kunnr = ivbrk-kunag binary search. Get the reference division to be used for pricing clear i_tvkos. read table itvkos with key spart = imara-spart binary search. if sy-subrc ne 0. itvkos-spaku = vnref_spart. endif. clear i_knvv. read table iknvv with key kunnr = ivbrk-kunag vkorg = i_vbrk-vkorg vtweg = i_vbrk-vtweg spart = i_tvkos-spaku binary search. check sy-subrc = 0. read table it683v with key spart = vnref_spart kalks = i_knvv-kalks binary search. check sy-subrc eq 0. clear i_mcha. read table imcha with key matnr = sfpmatnr werks = i_vbrp-werks charg = i_vbrp-charg binary search. move-corresponding ikna to ikomk. move-corresponding iknvv to ikomk. ikomk-zzbran1 = ikna-bran1.

ikomk-zzbran2 = ikna-bran2. refresh ivbpav. clear ivbpav. call function ‘SDCUSTOMERHIERARCHY_PATH’ exporting customer = i_komk-kunnr htype = ‘A’ saleschannel = ikomk-vtweg salesdivision = vnref_spart salesorg = ikomk-vkorg importing customerhzuor = vhzuor tables hpath = i_vbpav exceptions hitypnotexist = 01 nodenotexist = 02 parvwnotexist = 03 others = 99. endform. ‘ SETUPFORPRICING. [Note: Before calling the FM within LOOP and populating the table parameter in the FM, it is always a good practice to clear and refresh the Table parameter internal table. After doing it cross check the three things like total number of entries, validation of the entries, and SE30 Bar chart load analysis. For example, CLEAR: ptabchghist[]. LOOP AT ptabchgheader. REFRESH ltabchghist. CALL FUNCTION ‘CHANGEDOCUMENT_READ’ EXPORTING changenumber = ptabchgheader-changenr objectclass = ptabchgheader-objectclas objectid = ptabchgheader-objectid TABLES editpos = ltabchghist EXCEPTIONS nopositionfound = 1

wrongaccessto_archive = 2 timezoneconversion_error = 3. IF sy-subrc = 0. LOOP AT ltabchghist. MOVE-CORRESPONDING ltabchghist TO ptabchghist. ptabchghist-ctltabkey = ltabchghist-tabkey. APPEND ptabchghist. ENDLOOP. ENDIF ENDLOOP. ] Case 3: LOOP AT ltresult INTO lsresult WHERE warpl IS INITIAL OR warpl EQ space. CLEAR: ls_result-mrmax, ls_result-rdtot, ls_result-delta, ls_result-overdue, ls_result-mrngu, ls_result-nplda. MODIFY ltresult FROM lsresult INDEX sy-tabix. ENDLOOP. Avoid SELECT...ORDER BY . Preferred to put the records into an internal table and then perform a SORT. Your Strategy during doing Performance enhancement of code before making any change. Do sql trace (ST05) and check the red colored affected select statements (net time) and save it as a print screen in a .doc file. Note: In case of timeout case, in Debugging mode see which Select query is taking more time / or which Select query is causing timeout cases and make correction in that Select query only. After making changes take sql trace (st05) screenshot for the previously affected red colored select statements (net time) and compare the object performance before and after making the required changes. During making your modification, under your Modification Tag, 1st Comment off the original code and then below that insert your new code having modification, then end your Modification tag. So during modification, please don’t delete any original source code or don’t put directly your modified code in the original existing code. *-Begin of insert by symmalaks on 28.01.2008 MOVE-CORRESPONDING ILIKP TO TVTTP. MOVE: ilikp-vbeln TO tvttp-vbeln, ilikp-vstel TO tvttp-vstel,

ilikp-kunnr TO tvttp-kunnr, ilikp-lfdat TO tvttp-lfdat, ilikp-wadat TO tvttp-wadat, ilikp-wadatist TO tvttp-wadatist, ilikp-volum TO tvttp-volum, ilikp-route TO tvttp-route, ilikp-lifex TO tvttp-lifex, ilikp-vgbel TO tvttp-vgbel, ilikp-name1 TO tvttp-name1. *-End of insert by symmalaks on 28.01.2008 Second Object Performance Analysis A) Performance (Some areas within the source code where performance needs to be enhanced) ZPSSAPFABTRACK In FM ZPS_SAPFABPO source code, Check Driver table gtabekko / ptab_ekko IS NOT INITIAL before using SELECT FOR ALL ENTRIES, currently this check is not present. SELECT * FROM ekko INTO TABLE ptab_ekko FOR ALL ENTRIES IN gtabekko WHERE ebeln = gtabekko-ebeln. and ekgrp = p_ekgrp and bukrs = p_bukrs and ekorg = p_ekorg and memory = space. “indicates complete PO CLEAR ptab_ekpo[]. SELECT * FROM ekpo INTO TABLE ptab_ekpo FOR ALL ENTRIES IN ptab_ekko WHERE ebeln = ptab_ekko-ebeln. SELECT * FROM ekko INTO TABLE ptab_ekko FOR ALL ENTRIES IN gtabekko WHERE ebeln = gtabekko-ebeln AND ekgrp = pekgrp AND bukrs = pbukrs AND ekorg = p_ekorg AND memory = space. “indicates complete PO IF sy-subrc = 0. SELECT * FROM ekpo INTO TABLE ptab_ekpo FOR ALL ENTRIES IN ptab_ekko WHERE ebeln = ptab_ekko-ebeln

AND knttp = pknttp AND pstyp = lpstyp AND werks = p_werks. ENDIF. Always use Binary search during using READ Statement. Before using Binary search we need to sort that internal table by that key. Remove PO headers without line LOOP AT ptab_ekko. READ TABLE ptabekpo WITH KEY ebeln = ptabekko-ebeln. IF sy-subrc = 0 . CONTINUE. ELSE. DELETE ptab_ekko. ENDIF. ENDLOOP. Within FORM getmissingitemheader in Include LZPSSAPFABTRACK Source code, LOOP AT ptabekpo. READ TABLE ptabekko WITH KEY ebeln = ptabekpo-ebeln. IF sy-subrc 0. CLEAR ptabekko. ptabekko-ebeln = ptabekpo-ebeln. APPEND ptabekko. ENDIF. ENDLOOP. In I nclude LZPSSAPFABTRACK Source code, Within FORM getcputimeparms, Avoid SELECT...OR and also Select/ Endselect, also avoid SELECT * Preferred to put the records into an internal table and then perform a SORT. SELECT * FROM zpsifctl WHERE zssbatchtype = pcbatchtype ORDER BY cpudt DESCENDING cputm DESCENDING. pddatefrom = zpsifctl-cpudt. pttimefrom = zpsifctl-cputm. pddateto = ‘99991231’. pttimeto = ‘235959’. EXIT. ENDSELECT. In the below statement in addition to the above checks, additionally check the sequence of fields in the WHERE Clause.

SELECT * FROM zpsifctl WHERE cpudt < pddateto OR ( cpudt = pddateto AND cputm < pttimeto ) AND zssbatchtype = pcbatchtype ORDER BY cpudt DESCENDING cputm DESCENDING. pddatefrom = zpsifctl-cpudt. pttimefrom = zpsifctl-cputm. EXIT. ENDSELECT. Remove MOVE-CORRESPONDING within loop and use the alternate correct MOVE statement for each field LOOP AT ltabchghist. MOVE-CORRESPONDING ltabchghist TO ptabchghist. ptabchghist-ctltabkey = ltabchghist-tabkey. APPEND ptabchghist. ENDLOOP. Note : Here, ptabchghist and ltabchghist have similar structures. ptabchghist[] = ltabchghist[]. DATE : ltabchghist LIKE gtabchghist OCCURS 0 WITH HEADER LINE. FORM filterpochghistory TABLES ptabchghist STRUCTURE gtabchghist. DATA: BEGIN OF gtabchghist OCCURS 0, ctltabkey LIKE cdred-tabkey. INCLUDE STRUCTURE cdred. DATA: END OF gtabchghist. Use Parallel cursor technique wherever possible for nested Loop. Within FORM processpodata, Use Parallel cursor technique during LOOP AT ptekko. LOOP AT ptekpo WHERE ebeln = ptekko-ebeln. ENDLOOP. ENDLOOP. In the above case in the above form, Remove MOVE-CORRESPONDING within loop and use the alternate correct MOVE statement for each field, also use Binary search during using READ Statement. Before using Binary search we need to sort that internal table by that key. Also, avoid select statement within Loop in the above form.

MOVE-CORRESPONDING ptekko TO gtabsapfab. MOVE-CORRESPONDING ptekpo TO gtabsapfab. 1. Avoid SELECT*, only select necessary fields in Select query CLEAR: gtabcdhdr[]. IF NOT po_number IS INITIAL. SELECT * FROM cdhdr INTO TABLE gtabcdhdr WHERE objectclas = gc_objclaspo AND objectid = po_number. ELSE. SELECT * FROM cdhdr INTO TABLE gtabcdhdr WHERE objectclas = gc_objclaspo AND ( udate > gdcpudtfrom OR ( udate = gdcpudtfrom AND utime > gtcputmfrom ) ) AND ( udate < gdcpudtto OR ( udate = gdcpudtto AND utime < gtcputmto ) ). ENDIF. 1. Avoid Nested Select in Include LZPSSAPFABTRACK_POF01in FORM getcputimeparms. SELECT SINGLE * FROM zpsifctl WHERE zssbatchid = pcbatchid AND zssbatchtype = pcbatchtype. IF sy-subrc = 0. pddateto = zpsifctl-cpudt. pttimeto = zpsifctl-cputm. pddatefrom = ‘19000101’. pttimefrom = ‘000001’. SELECT * FROM zpsifctl WHERE cpudt < pddateto OR ( cpudt = pddateto AND cputm < pttimeto ) AND zssbatchtype = pcbatchtype ORDER BY cpudt DESCENDING cputm DESCENDING. pddatefrom = zpsifctl-cpudt. pttimefrom = zpsifctl-cputm.

EXIT. ENDSELECT. ENDIF. NOTE

12 chapter Earn Value - Overview What do you find in this chapter? 12.1 INTRODUCTION

Earned Value Mana ( EVM ) is a project management technique that objectively tracks physical accomplishment of work. EVM is used to track the progress and status of a project and forecasts the likely future performance of the project. EVM integrates the scope, schedule, and cost of a project. EVM answers a lot of questions to the stakeholders in a project related to its performance. EVM can be used to show the past and the current performance of a project and predict the future performance of the project by the use of statistical techniques. Good planning coupled with effective use of EVM will reduce a lot of issues arising out of schedule and cost overruns. 12.2 OVERVIEW EVM consists of the following three basic elements: Planned Value Actual Cost Earned Value All the three elements are captured on a regular basis as of a reporting date Planned Value Planned value (PV) is also referred to as Budgeted Cost of Work Scheduled (BCWS). PV or BCWS is the total cost of the work sched uled.pl an ned as of a reporting date It is calculated as: PV or BCWS = Hourly Rate x Total Hours Planned or Scheduled NOTE Hourly Rate is the rate at which effort will be valued Actual Cost Actual cost (AC) is also referred to as Actual Cost of Work Performed (ACWP). AC or ACW'P is the total cost taken to complete the work as of a reporting date. It is calculated as: AC or ACWP = Hourly Rale x Total Hours Spent % Completed Planned The percentage of work which was planned to be completed by the Reporting Date. It is calculated using the following formula: % Completed Planned = PV/BAC % Completed Actual The percentage of work which was actually completed by the Reporting Date It is calculated using the following formula: % Completed Actual = AC / EAC Cost Valance (CV) is a very important factor to measure project performance. CV indicates how much over- or under-budget the project is. It is calculated as: Cost Variance (CV) = Earned Value (EV) - Actual Cost (AC) OR

Cosl Variance (CV) = Earned Value (EV) - Actual Cost (AC) The formula mentioned above gives the variance in lerms of cost Positive CV indicates the project is under-budget. Negative CV indicalesthe projecl is over-Dudget. Cosl Variance % Cosl Variance % indicates how much over - or under-budget the projecl is in terms of percentage. It is calculated as: CV % = Cost Variance (CVj/Earned Value (EV) OR CV % = CV/BCYYP The formula mentioned for Cot variances in lerms of percentage. Positive Variance % indicates % under budget Negative Variance % indicates % over budget. Cost Performance Indicator Cost Performance Indicator (CPI) is an index showing the efficiency of the utilization of the resources on the project. It can be calculated as CPI = Earned Value (EV)/Actual Cost (AC) OR CPI = BCWP/ACWP The formula mentioned above gives the efficiency of the utilization of the resources allocated to the project. A CPI value above 1 indicates the efficiency of utilizing the resources allocated to the project is good A CPI value below 1 indicates the efficiency of utilizing the resources allocated to the project is not good. To Complete Cos1 Performance Indicator To Complete Cost Performance Indicator (TCPI) is an index showing the efficiency at which the resources on 1he project should be utilized for the remainder of the project It can be calculated as TCPI = ( Total Budgel - EV )/( Total Budgel - AC ) OR TCPI = ( Total Budgel - BCWP )/( Tolal Budget - ACWP ) The formula mentioned above gives the efficiency at which the project team should be utilized for the remainder of the project. A TCPI value above 1 indicates the utilization of the project team for the remainder of the project can be stringent. A TCPI value below 1 indicates the utilization of the project team for the remainder of the project should be lenient. Schedule Variance (SV) indicates how much ahead or behind the schedule a project is running. It can be calculated as Schedule Variance (SV) = Earned Value (EV) - Planned Value (PV)

OR Schedule Variance (SV) = BCWP - BCWS The formula mentioned above gives the variance in ferms of cost which indicates flow much cost of the work is yet to be completed as per schedule or how much cost of work has been completed over and aoove the scheduled cost. A positive SV indicates we are ahead of schedule. A negative SV indicates we are behind schedule. Schedule Variance % Schedule Variance % indicates how much ahead or behind (he schedule a project is running in terms of percentage. It can be calculated as SV % = Schedule Variance (SV)/Planned Value (PV) OR SV % = SV/BCWS The formula mentioned above gives the variance in lerms of percentage which indicates how much percentage of work is yet to be completed as per schedule or how much percentage of work has been completed over and above the scheduled cost. Positive Variance % indicates % ahead of schedule. Negative Variance % indicates behind of schedule. Schedule Performance Indicator Schedule Performance Indicator (SPI) is an index showing the efficiency of the time utilized on the project. SPI can be calculated using the following formula: SPI = Earned Value (EV)/Planned Value (PV) OR SPI = BCWP/BCWS The formula mentioned above gives the efficiency of the project team in utilizing the time allocated for the project. An SPI value aDove 1 indicates the projed team is very efficient in utilizing the time allocated 1e the project. An SPI value below 1 indicates the project team is less efficienl in utilizing the time allocated to the project. To Complete Schedule Performance Indicator To Complete Schedule Performance Indicator (TSPI) is an index showing the efficiency al which the remaining time on the project should De utilized. I It can be calculated as TSPI = ( Tolal Budget - EV )/( Tolal Budget - PV ) OR TSPI = ( Tolal Budget - BCWP )/(Total Budget - BOWS ) The formula mentioned above gives the efficiency at which the project team should utilize the remaining time allocated for the project A TSPI value below 1 indicates the project team can be lenient in utilizing Ihe remaining time allocated to the project. A TSPI value above 1 indicates the project team needs to work harder in utilizing the remaining time allocated to the project Budget at Completion

It can be calculated as Estimate to Complete 12.3 PROJECT MANAGERS COST FORMULAS

NOTE

13 chapter Basic OData Services Using SAP NetWeaver Gateway 2.0 What do you find in this chapter? 13.1 INTRODUCTION Developing OData Services Using SAP Net Weaver Gateway is designed to enable ABAP developers develop backend services that will allow consumer devices to consume SAP business data in an easy to use manner using open standards. 13.2 REQUIRED SKILLS ABAP Workbench Foundation

ABAP Objects 13.3 OPTIONAL SKILLS High level understanding of Web based communication (i.e. HTTP) 13.4 SOFTWARE PRE-REQUISITES SAP NetWeaver Gateway Foundation SAP_GWFND 13.5 OBJECTIVES At the end of this course, you should be able to learn: Note : Several diagrams are taken directly from SAP documentation in this course material. 13.6 SAP USER EXPERIENCE JOURNEY

The SAP user expe ( UX ) strategy is aimed at bringing great products to customers. Using the principles of design thinking, maintain the core value of listening to our customers’ needs and quickly incorporating their feedback into SAP products. With the influence of consumer software making its way into the enterprise, SAP’s UX strategy aims to meet users’ expectations of easy-to-use software in the workplace. Provide consumer-grade UX for new applications. Renew existing applications by improving the UX for the most commonly-used business scenarios. Enable customers with tools to improve the UX of the SAP software. Core to SAP’s user experience strategy of new, renew and are SAP Fiori UX and SAP Screen Personas.

What is SAP NetWeaver Gateway? SAP NetWeaver Gateway is a technology that provides a simple way to connect devices, environments and platforms to SAP software based on market standards. The framework enables development of innovative people centric solutions bringing the power of SAP business software into new experiences such as social and collaboration environments, mobile and tablet devices and rich internet applications. In simple words Netweaver Gateway is a set ofABAP add-ons to your existing SAP ERP system that provides easy access to your business information in a simple, people-centric manner and lowers the data consumption barrier to the point that no prior knowledge of an SAP system’s internal workings is required. The Gateway provides an API that is designed to function as easy—to—use, well defined that gives access to the rich wealth of business data and functionality in your SAP systems. Consumption of data through the SAP NetWeaver Gateway interface requires nothing more than the ability to make an HTTP(S) request (something any browser can do); in other words, it does not require the use of any SAP proprietary software or protocols. From the perspective of a client application developer, the SAP NetWeaver Gateway interface does not impose any requirement on them to be able to write software in ABAP, or even to have any understanding of the internal workings of a SAP system.

SAP NetWeaver Gateway offers connectivity to SAP applications using any programming language or model without the need for SAP knowledge by leveraging REST services and OData/ATOM protocol. 13.7 SAP NETWEAVER GATEWAY ARCHITECTURE

13.8 DEPLOYMENT OPTION SAP NetWeaver Gateway can be installed independent of consumer technologies, however the software components installed for the consumer technologies must also be installed on one SAP NetWeaver Gateway server. Multiple consumer technologies can be connected to one SAP NetWeaver Gateway instance. Deployment Options Embedded depl The core components for SAP NetWeaver Gateway and any optional backend components are deployed together in the SAP Business Suite backend system. For this deployment option, you need a backend system only, and not a dedicated SAP NetWeaver Gateway central hub system. SAP component GWCORE and IWBEP are installed in the same system. Central hub depl The SAP NetWeaver Gateway core components can be deployed in a standalone system, either behind or in front of the firewall. In addition, you can install the optional components for central hub deployment in your standalone system. For SAP NetWeaver 7.02, 7.03, and 7.31 you can install the component IWBEP either in this hub system and/or in the backend system. For SAP NetWeaver 7.40 and higher, the core component SAPGWFND is installed as standard and includes the functional scope of IW_BEP. 13.9 REST DEFINITION REST stands for Representational State Transfer which is a style of software architecture for distributed systems such as the Wortd Wide Web. REST defines 6 architectural constraints Communication between participants must: Implement Client-Server model Be layered Be Stateless Be Uniform Server responses must deline whether or not they are Cacheable The Server should be able to deliver Code-On-Demand to the client

RESTful applications use HTTP requests to post data (creale and/or updale). read data [e.g., make queries), and delete dala. Thus. REST uses HTTP for all four CRUD

(Creale/Read/Update/Delete) operations REST uses the standard GET. PUT. POST 6 DELETE methods and olher existing features of the HTTP protocol. As a programming approach, REST is a lightweight alternative to Web Services.