Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[ABAP] Z_CLEANUP_LRQ_WORKFLOWS

A cleanup report I’ve written some years ago, to end incomplete leave request workflows. I couldn’t figure out why some workflows hadn’t been completed over the years. Since the absences were from a long time ago, the goal was simply to clean up the system. Maybe someone else will need to do something similar someday.

*&---------------------------------------------------------------------*
*& Report Z_CLEANUP_LRQ_WORKFLOWS
*&---------------------------------------------------------------------*
*& This report was written to end old absence request workflows,
*& where the absence request got already approved,
*& but somehow the WF got not set to status 'COMPELTED'.
*& https://me.sap.com/notes/0002650820
*&---------------------------------------------------------------------*
REPORT z_cleanup_lrq_workflows.

TABLES: ptreq_header, swwwihead, pa0002.

TYPES:
  BEGIN OF ty_log,
    icon          TYPE icon-id,
    objid         TYPE objektid,
    vorna         TYPE vorna,
    nachn         TYPE nachn,
    request_id    TYPE ptreq_header-request_id,
    version_no    TYPE tim_req_version,
    request_type  TYPE tim_req_type,
    status        TYPE tim_req_status,
    mod_timestamp TYPE timestamp,
    timestamp     TYPE string,
    workitem_id	  TYPE sww_wiid,
    wi_stat       TYPE sww_wistat,
    wi_stat_new   TYPE sww_wistat,
    comment       TYPE string,
  END OF ty_log.

DATA gt_log     TYPE TABLE OF ty_log WITH DEFAULT KEY.
DATA return     TYPE TABLE OF swl_return.
DATA new_status TYPE sww_wistat.
DATA status     TYPE ptarq_uia_request-status.

INITIALIZATION.

  SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE TEXT-b01.

    SELECT-OPTIONS: s_pernr FOR pa0002-pernr              MATCHCODE OBJECT prem,
                    s_guid  FOR ptreq_header-request_id,
                    s_rtype FOR ptreq_header-request_type DEFAULT 'ABSREQ',
                    s_statu FOR status                    DEFAULT 'POSTED',
                    wi_stat FOR swwwihead-wi_stat         DEFAULT 'STARTED'.

    PARAMETERS: fdate  TYPE datum DEFAULT '20180101',
                ftime  TYPE tims,
                tdate  TYPE datum DEFAULT '20231231',
                ttime  TYPE tims,
                p_test AS CHECKBOX DEFAULT abap_true.

  SELECTION-SCREEN END OF BLOCK b1.

START-OF-SELECTION.

  CONVERT DATE fdate TIME ftime INTO TIME STAMP DATA(ts_from) TIME ZONE 'UTC'.
  CONVERT DATE tdate TIME ttime INTO TIME STAMP DATA(ts_upto) TIME ZONE 'UTC'.

  SELECT a~request_id, a~version_no, a~status, a~request_type, a~mod_timestamp, a~workitem_id, b~objid, c~wi_stat, d~vorna, d~nachn
    FROM ptreq_header    AS a
        JOIN ptreq_actor AS b ON a~initiator_ins = b~actor_id
        JOIN swwwihead   AS c ON a~workitem_id   = c~wi_id
        JOIN pa0002      AS d ON b~objid         = d~pernr
    INTO CORRESPONDING FIELDS OF TABLE @gt_log
    WHERE a~request_id    IN @s_guid
      AND a~status        IN @s_statu
      AND a~request_type  IN @s_rtype
      AND a~mod_timestamp BETWEEN @ts_from AND @ts_upto
      AND b~objid         IN @s_pernr
      AND c~wi_stat       IN @wi_stat.

END-OF-SELECTION.

  LOOP AT gt_log ASSIGNING FIELD-SYMBOL(<log>).

    <log>-timestamp = |{ <log>-mod_timestamp TIMESTAMP = ENVIRONMENT }|.

    IF p_test = abap_true.
      <log>-comment = |Testrun! No workflow changed!|.
      CONTINUE.
    ENDIF.

    IF <log>-wi_stat <> |STARTED|. CONTINUE. ENDIF.

    CALL FUNCTION 'SWL_ADM_WI_COMPLETE'
      EXPORTING
        wi_id                         = <log>-workitem_id
      TABLES
        return                        = return
      EXCEPTIONS
        workitem_not_found            = 1
        no_authority                  = 2
        wrong_workitem_type           = 3
        workflow_definition_not_found = 4
        internal_error                = 5
        action_canceled               = 6
        OTHERS                        = 7.
    IF sy-subrc <> 0.
      <log>-icon    = icon_red_light.
      <log>-comment = COND #( WHEN lines( return ) > 0 THEN return[ 1 ]-text
                                                       ELSE SWITCH #( sy-subrc WHEN 1 THEN |workitem_not_found|
                                                                               WHEN 2 THEN |no_authority|
                                                                               WHEN 3 THEN |wrong_workitem_type|
                                                                               WHEN 4 THEN |workflow_definition_not_found|
                                                                               WHEN 5 THEN |internal_error|
                                                                               WHEN 6 THEN |action_canceled|
                                                                               WHEN 7 THEN |OTHERS| ) ).
    ELSE.
      " Check if WF status really got changed
      SELECT SINGLE wi_stat FROM swwwihead INTO <log>-wi_stat_new WHERE wi_id = <log>-workitem_id.
      <log>-icon    = COND #( WHEN <log>-wi_stat_new <> |COMPLETED| THEN icon_red_light ELSE icon_green_light ).
      <log>-comment = COND #( WHEN <log>-wi_stat_new <> |COMPLETED| THEN |Something went wrong!| ).
    ENDIF.

  ENDLOOP.


  IF gt_log IS INITIAL.
    MESSAGE i002(wusl) DISPLAY LIKE 'E'.
  ELSE.
    TRY.
        cl_salv_table=>factory( IMPORTING r_salv_table = DATA(alv_table)
                                CHANGING  t_table      = gt_log ).

        alv_table->get_columns( )->get_column( 'ICON'          )->set_long_text( 'Icon' ).
        alv_table->get_columns( )->get_column( 'WI_STAT_NEW'   )->set_long_text( 'Neuer WF Status' ).
        alv_table->get_columns( )->get_column( 'WI_STAT_NEW'   )->set_medium_text( 'Neuer Status' ).
        alv_table->get_columns( )->get_column( 'COMMENT'       )->set_long_text( 'Kommentar' ).
        alv_table->get_columns( )->get_column( 'TIMESTAMP'     )->set_long_text( 'Letzte Änderung' ).
        alv_table->get_columns( )->get_column( 'COMMENT'       )->set_output_length( 100 ).
        alv_table->get_columns( )->get_column( 'TIMESTAMP'     )->set_output_length( 20 ).
        alv_table->get_columns( )->get_column( 'MOD_TIMESTAMP' )->set_visible( abap_false ).

        alv_table->display( ).

      CATCH cx_root.
    ENDTRY.
  ENDIF.

[Fiori] Abwesenheitsantrag in Inbox für nicht genehmigungspflichtige Abwesenheitsart

Kürzlich hatte ich die Situation, dass eine Führungskraft einen Abwesenheitsantrag in der Inbox hatte für eine Abwesenheitsart, die eigentlich nicht genehmigungspflichtig ist. Es hätte also gar kein Genehmigungsworkflow gestartet werden dürfen. Merkwürdigerweise war die beantragte Abwesenheit auch bereits im Infotyp verbucht. Auch konnte man den Antrag in der Inbox weder Ablehnen noch Genehmigen, beides lief auf ein Fehler.

Wie kam es also zu dieser Situation?

Der Mitarbeiter hatte einen Antrag mit einer genehmigungspflichtigen Abwesenheitsart gestellt, wie z.B. Urlaub.

Bevor der Genehmiger diesen Antrag bearbeitet hat, wurde der Antrag vom Antragsteller jedoch nochmal abgeändert. Dies ist über das Stift-Symbol möglich. Dabei wurde dann eine nicht genehmigungspflichtige Abwesenheitsart gewählt, wie z.B. Abbau Überzeit.

In diesem Fall wird der Antrag ohne Genehmigungsprozess durchlaufen und die Abwesenheit wird kurz darauf direkt in den Infotyp geschrieben durch den Verbucherreport.

Jedoch gab es ja bereits einen laufenden Workflow mit einem Workitem in der Inbox des Genehmigers und dieser wurde nicht beendet. Stattdessen wurde in dem Workitem sogar die beantragte Abwesenheitsart aktualisiert, obwohl für diese Abwesenheitsart ja gar keine Genehmigung erforderlich ist und sogar bereits in den Infotyp geschrieben war.

Auch in der Antragsdatenbank spiegelt sich das Problem wider. Der Antrag stand dort im Status ‘POSTED‘ und der Workflow-Status auf ‘STARTED‘.

Ich habe das Szenario dann mit einer Zweiten, nicht genehmigungspflichtigen Abwesenheitsart getestet, also Urlaub erfasst und vor Genehmigung die Abwesenheitsart geändert. Hier wurde jedoch der laufende Workflow korrekterweise beendet.

Als ich beide Abwesenheitsarten in der V_T554S_WEB verglichen habe, ist mir aufgefallen, dass bei der problembehafteten Abwesenheitsart ein Workflow gecustomized war, obwohl diese ja nicht genehmigungspflichtig ist. Der Workflow wurde jedoch nur verwendet, um eine Info-Mail zu versenden.

Die Workflow Checkbox ließ sich leider nicht deaktivieren (vermutlich weil es schon Anträge zu der Abwesenheitsart gibt). Aber es scheint, als führt dieses Workflowcustomizing dann zu Inkonsistenzen, wenn in einem laufenden Antrag von einer genehmigungspflichtigen Abwesenheitsart zu einer nichtgenehmigungspflichtigen gewechselt wird.

Dieser Post nur als Erinnerung, falls ich nochmal in so eine Situation laufe. Vielleicht habe ich dann die Chance, es zu verifizieren.

[Fiori] MyInbox – Leave Request Approval: Genehmigung erfolgreich, aber mit Fehler für Workflow 21500001

Beim Einrichten der 1-Stufigen Genehmigung von Urlaub mit dem Standard Workflow 21500001 bin ich in folgenden Fehler gelaufen in der Inbox nach Drücken des Genehmigungsbuttons.

Merkwürdigerweise wurde der Urlaubsantrag erfolgreich genehmigt und trotzdem gab es eine Fehlermeldung. Nach kurzem debuggen war auch klar warum. Der Antrag wurde erst erfolgreich genehmigt und dann wurde das gleiche Coding nochmal durchlaufen und führte zu einer Kollisionsmeldung.

Daraufhin habe ich mir den BAdI /IWWRK/BADI_WF_BEFORE_UPD_IB angeschaut. Dort konnte ich zwei Implementierungen zum Thema Leave Approval finden und in beiden war der Workflow 21500001 als Filterkriterium eingetragen. Das erklärte, warum die Genehmigungslogik zweimal durchlaufen wurde.

Daraufhin habe ich nach einem Hinweis gesucht und folgenden gefunden: 2658528. Der beschreibt zwar eine andere Fehlermeldung, aber die Lösung war genau die Aussage, die ich gesucht habe.

Die Implementierung HRMSS_LEAVE_APPROVAL musste also deaktiviert werden. Ich habe das über die SE19 gemacht, auch wenn das bedeutete, dass ich nun als letzter Änderer eines SAP-Objekts drin stehe. Anscheinend geht es auch über den Funktionsbaustein ENH_BADI_IMG_ACTIVITY_TOGGLE wie hier beschrieben.

[Fiori] Send notification mail if workitem is forwarded in MyInbox

Workitem function modules

If you forward a workitem manually from the MyInbox or via function module SAP_WAPI_FORWARD_WORKITEM, the function module SWW_WI_FORWARD will be called. There the SAP implemented a BAdI call of the BAdI WF_WI_FORWARD.

BAdI WF_WI_FORWARD

The BAdI provides a method to add additional checks, when forwarding a workitem. I will use it, to send notification mails.

BAdI Filter

Create your own BAdI implementation and add a task id as filter. In my case it’s the task TS21500003 of the leave request approval workflow.
Now your implementation will only be called, if this specific workitem is forwarded. Now we implement the method CHECK_BEFORE_FORWARD. The method has enough parameters to get all necessary information to enrich the mail text.

IF_EX_WF_WI_WORKITEM~CHECK_BEFORE_FORWARD Paramter

First the workitem container is read out of the context. There we get the _WI_OBJECT_ID element, which contains the request object reference. With this information we are able to get the current request object out of the workflow. I pass this into antother class where I already have a mail sending implementation.

  METHOD if_ex_wf_wi_workitem~check_before_forward.
*---------------------------------------------------------------------------------*
* This BAdI implementation is used to send an info mail when a workitem is forwarded.
*---------------------------------------------------------------------------------*

    TRY.

        "Get workitem container and requestId
        DATA(container) = im_workitem_context->get_wi_container( ).

        container->get_value_ref( EXPORTING name       = |_WI_OBJECT_ID|
                                  IMPORTING value_ref  = DATA(lr_req_id) ).

        ASSIGN lr_req_id->* TO FIELD-SYMBOL(<lpor>).

        "Get current request object
        DATA(lo_req) = NEW cl_pt_req_wf_attribs( )->bi_persistent~find_by_lpor( lpor = <lpor> ).

        "Send an info mail to each new agent (should be only one)
        LOOP AT im_table_new_agents INTO DATA(new_agent).
          zcl_hcm_leave_request_assist=>send_mail( io_req         = CAST cl_pt_req_wf_attribs( lo_req )
                                                   iv_tdname      = mc_mailtext
                                                   iv_pernr       = cl_hcmfab_employee_api=>get_instance( )->get_employeenumber_from_user( iv_user = new_agent-objid ) ).
        ENDLOOP.


      CATCH cx_hcmfab_common.
      CATCH cx_swf_cnt_elem_not_found.
      CATCH cx_swf_cnt_container.
        "In error case, do nothing. The workitem should still be forwarded.
        RETURN.
    ENDTRY.

    "Write Info to WF Log
    MESSAGE s001(00) WITH |Forward: Mail { mc_mailtext }| INTO DATA(lv_message).
    im_workitem_context->set_message_to_log( im_function = CONV #( lv_message )         "max char30
                                             im_message = VALUE #( msgid = sy-msgid
                                                                   msgty = sy-msgty
                                                                   msgno = sy-msgno
                                                                   msgv1 = sy-msgv1 ) ).
    COMMIT WORK.
  ENDMETHOD.

At the end I’m writing a little notification in the workflow log. The workitem context provides the method set_message_to_log for this. The log will look like this.

[ABAP] Access leave request attributes

cl_pt_req_badi=>get_request( EXPORTING im_req_id  = request_id
                             IMPORTING ex_request = DATA(request) ).

request->get_all_attribs( IMPORTING ex_attribs_struc = DATA(req_attribs) ).

DATA(req_begda) = req_attribs-version-item_tab[ 10 ]-value.

Take a look in the item_tab to see the specific request values.

[Fiori] Leave Request Approval Steps with Custom Workflow

If you want to copy the standard workflow of the leave request approval process (WS12300111) and are adding another approval step (or you just want to add an escalation where you set the approve workitem to obsolete and create a new approval step for the next approver) you have to implement the following BAdI. In detail you only have to add the new step ID in the filter, else the approver will not see any approval or reject buttons in his inbox. See details here.

BAdI: /IWWRK/BADI_WF_BEFORE_UPD_IB

Default implementation: HCMFAB_LEAVE_APPROVAL_INBOX
Default Workflows and Step ID’s
Add your custom workflow and the custom approval step id in your own BAdI implementation

As second step you have to add the Workflow in the customizing. You’ll find further information here.

SM30 View /IWWRK/V_WFSTEP.
Add the Workflow with Approval StepId
Add the Approve and Reject Buttons

[ABAP] Leave Request Approval Workflow with Escalation

The standard workflow WS12300111 for the leave request approval process does not include any deadlines. To achieve this you can simply copy the workflow and add a deadline at the approval task (Step 38). There are two possible ways to forward the approval step to the next processor:
1. When deadline is reached, forward the current workitem to the next approver.
2. When deadlines is reached, set current workitem to obsolete and create a new workitem and assign it to the next approver. Then you also have to add the new step ID to this BAdI Filter.

I selected the first option. In my demo the escalation is triggered after just three minutes.

The deadline generates a new exit on the approval step.

In this new exit you are able to call your own logic on finding the new approver, forward the workitem and inform him via mail if necessary.

To forward the request to the next approver, you have to forward the workitem and also set this new approver as next processor in the current leave request.
So first identify the next approver. I used RH_GET_LEADER for this.

*--------------------------------------------------*
* Get next approver
*--------------------------------------------------*
    CALL FUNCTION 'RH_GET_LEADER'
      EXPORTING
        plvar                     = '01'
        keydate                   = sy-datum
        otype                     = is_approver-otype
        objid                     = CONV realo( is_approver-objid )
      IMPORTING
        leader_type               = lv_leader_type
        leader_id                 = lv_leader_id
      EXCEPTIONS
        no_leader_found           = 1
        no_leading_position_found = 2
        OTHERS                    = 3.

    CHECK lv_leader_type EQ 'P' AND lv_leader_id IS NOT INITIAL.

    CALL FUNCTION 'HR_GET_USER_FROM_EMPLOYEE'
      EXPORTING
        pernr             = CONV pernr_d( lv_leader_id )
        iv_with_authority = abap_false
      IMPORTING
        user              = lv_userid_approver.

    ev_approver-otype = |US|.
    ev_approver-objid = lv_userid_approver.


Then set this new approver as next processor in your request. While doing this, it’s recommended to enqueue and dequeue the request. To get the current request object use class cl_pt_req_badi.

*--------------------------------------------------*
* Set new approver in request
*--------------------------------------------------*
    " Enqueue the request
    CALL FUNCTION 'ENQUEUE_EPTREQ'
      EXPORTING
        mode_ptreq_header = 'S'
        mandt             = sy-mandt
        request_id        = io_req->req_id
      EXCEPTIONS
        foreign_lock      = 1
        system_failure    = 2
        OTHERS            = 3.

    " Get the request object instance
    CALL METHOD cl_pt_req_badi=>get_request
      EXPORTING
        im_req_id  = io_req->req_id
      IMPORTING
        ex_request = DATA(lcl_request).

    CALL METHOD lcl_request->set_next_processor
      EXPORTING
        im_actor_type = 'P'
        im_plvar      = '01'
        im_otype      = 'P'
        im_objid      = CONV #( lv_leader_id ). " PERNR of Next Approver
    IF sy-subrc = 0.
      COMMIT WORK AND WAIT.
    ENDIF.

    " Dequeue the request
    CALL FUNCTION 'DEQUEUE_EPTREQ'
      EXPORTING
        mode_ptreq_header = 'S'
        request_id        = io_req->req_id.

Finally forward the workitem to the new approver. There of course you need the right workitem ID of the approving step.

*--------------------------------------------------*
* Forward workitem to next approver
*--------------------------------------------------*
    CALL FUNCTION 'SAP_WAPI_FORWARD_WORKITEM'
      EXPORTING
        workitem_id  = iv_wi_id                "woritem id of approving step
        user_id      = lv_userid_approver
        language     = sy-langu
        do_commit    = 'X'
      IMPORTING
        return_code  = lv_subrc.
    IF lv_subrc <> 0.
    ENDIF.