SAP TM ABAP: Create Freight Orders and Assign Freight Units via BOPF

SAP TM ABAP: Create Freight Orders and Assign Freight Units via BOPF

Sooner or later every SAP TM project gets the request: “we already know which freight units go on which truck, so create the freight orders and assign them automatically.” The trigger is a Z report with an upload file, a Fiori app with a RAP backend, or an interface. The business logic is simple. Writing the code is where teams lose days.

The typical result: an empty freight order, an assignment action that returns no error, and freight units that are still unplanned. Or a RAP action that dumps on save. This article covers the BOPF calls that do the work, the checks that silently block an assignment, and how to wrap the whole thing for mass processing and for RAP.

1) Context: one business object, two document categories

Everything here applies to embedded TM in S/4HANA and standalone TM 9.x: both use the BOPF business object /SCMTMS/TOR. Freight units, freight orders and bookings are all its instances. The root field TOR_CAT tells them apart (FU for a freight unit, TO for a freight order, BO for a booking), and TOR_TYPE carries the document type from customizing. Root data is stored in /SCMTMS/D_TORROT, items in /SCMTMS/D_TORITE and stops in /SCMTMS/D_TORSTP.

The detail that explains most failed assignments: what gets assigned are freight unit stages, not items. After a successful assignment, the stop instances of the freight unit point to the corresponding stop instances of the freight order. If the system cannot find or build a matching stage on the freight order, nothing is linked.

Where the two deployments differ for this topic:

  • RAP and the background processing framework (bgPF) exist only on S/4HANA. Standalone TM 9.x uses a classic report.
  • From S/4HANA 2020 the freight order carries a procuring company code, and the freight order type can check it against the company code of each freight unit. Older releases do not run this check.
  • Before S/4HANA 2020, the TransportationOrderGenericRequest_In service could not assign freight units without an enhancement (more on that in section 5).

2) Creating the empty freight order with /SCMTMS/CL_TOR_FACTORY

The published examples for creating a freight order in code use /SCMTMS/CL_TOR_FACTORY=>CREATE_TOR_TOUR. Its main inputs are:

  • IV_TOR_TYPE: the freight order type from customizing. Pass the type a planner would use; it drives number range and follow-on settings.
  • IV_CREATE_INITIAL_STAGE: set to abap_true to get a first stage between source and destination stop.
  • IS_FO_INFO (structure /SCMTMS/S_TOR_FO_INFO): carries the source and destination location keys, not the location IDs. Convert location IDs to keys first.
  • IV_CREATION_TYPE: the manual creation constant from /SCMTMS/IF_TOR_CONST.

The method hands back the new root, item and stop data. In the examples it does not touch the BOPF buffer by itself. The caller turns that data into a modification table (the examples use /SCMTMS/CL_MOD_HELPER=>MOD_CREATE_MULTI), passes it to the service manager’s MODIFY, and then saves through the transaction manager. Read its full signature in SE24 before coding against it; some examples use the alternative CREATE_TOR_BO.

The freight order created this way has no freight units. Assignment is a separate step.

3) Assigning freight units with the ADD_FU_BY_FUID action

/SCMTMS/TOR offers three root actions for this. ADD_FU_BY_FUID takes freight unit numbers, ADD_FU_BY_BASEID works from the base document, and ADD_FUSTAGE_WITH_PLANNING works on requirement stages. Despite its name, that last one also accepts CU, PU, RU and TU stages. For a report that receives freight unit numbers, ADD_FU_BY_FUID is the natural fit.

Its parameter structure is /SCMTMS/S_TOR_A_ADD_ELEMENTS. Two components matter: STRING holds the freight unit IDs separated by newline, and TARGET_ITEM_KEYS takes the key of the vehicle item on the freight order the units should go onto. The action runs on the freight order root key, so the first job is converting the freight order number into a BOPF key through the TOR_ID alternative key.

PARAMETERS: p_fo  TYPE /scmtms/tor_id OBLIGATORY,
            p_fus TYPE string LOWER CASE OBLIGATORY. " FU IDs, comma separated

DATA: lt_fo_id    TYPE STANDARD TABLE OF /scmtms/tor_id WITH DEFAULT KEY,
      lt_fo_key   TYPE /bobf/t_frw_key,
      lt_failed   TYPE /bobf/t_frw_key,
      lo_message  TYPE REF TO /bobf/if_frw_message,
      lv_rejected TYPE abap_bool.

DATA(lo_srv) = /bobf/cl_tra_serv_mgr_factory=>get_service_manager( /scmtms/if_tor_c=>sc_bo_key ).
DATA(lo_tra) = /bobf/cl_tra_trans_mgr_factory=>get_transaction_manager( ).

APPEND p_fo TO lt_fo_id.                 " TOR_ID is an alternative key of ROOT
lo_srv->convert_altern_key(
  EXPORTING iv_node_key   = /scmtms/if_tor_c=>sc_node-root
            iv_altkey_key = /scmtms/if_tor_c=>sc_alternative_key-root-tor_id
            it_key        = lt_fo_id
  IMPORTING et_key        = lt_fo_key ).
IF lt_fo_key IS INITIAL.
  MESSAGE |Freight order { p_fo } not found| TYPE 'E'.
ENDIF.

SPLIT p_fus AT ',' INTO TABLE DATA(lt_fu_ids).
LOOP AT lt_fu_ids ASSIGNING FIELD-SYMBOL(<lv_id>).
  CONDENSE <lv_id>.
ENDLOOP.
DATA(lr_param) = NEW /scmtms/s_tor_a_add_elements( ).
" The action expects one FU ID per line
lr_param->string = concat_lines_of( table = lt_fu_ids sep = cl_abap_char_utilities=>newline ).

lo_srv->do_action( EXPORTING iv_act_key    = /scmtms/if_tor_c=>sc_action-root-add_fu_by_fuid
                             it_key        = lt_fo_key
                             is_parameters = lr_param
                   IMPORTING eo_message    = lo_message
                             et_failed_key = lt_failed ).

IF lt_failed IS INITIAL AND ( lo_message IS NOT BOUND OR lo_message->check( ) = abap_false ).
  lo_tra->save( IMPORTING ev_rejected = lv_rejected eo_message = lo_message ).
  IF lv_rejected = abap_true. lo_tra->cleanup( ). ENDIF.
ELSE.
  lo_tra->cleanup( ).                    " drop the buffer, release the locks
ENDIF.
" lo_message->get_messages( ) feeds the log, see section 6

CHECK( ) on the message object returns abap_true when it holds error messages, which is a stricter test than an empty ET_FAILED_KEY. CLEANUP( ) matters in loops: without it the next iteration still sees the rejected changes in the buffer. The example leaves TARGET_ITEM_KEYS empty. If the freight order has several capacity items, or the action ends without any link, retrieve the vehicle item from the ITEM_TR node and fill it.

4) Why the action succeeds and nothing is assigned

The most reported symptom is an action call with no failed keys and no messages, while the freight units stay unplanned. The reason is almost always in the stages.

Symptom Likely cause Where to look
No error, FU not linked FU stage does not match a stage on the FO (different source or destination) Compare the FU stops in /SCMTMS/D_TORSTP with the FO stops; try the same FU in the FO UI
Only some FUs linked Only FUs whose destination matches the FO destination were added Group FUs by source and destination before calling the action
FU cannot be inserted FO already has defined stages (KBA 2957842) Stages of the FO; the KBA describes the restriction
Vehicle, resource or TU cannot be assigned to the FO FO stage is planned to a schedule (KBA 2444548) Schedule reference on the FO
Company code error on S/4HANA 2020+ Procuring company code on the FO differs from the FU’s company code and Subcontract Checks are active FO header company code; freight order type customizing
Short dump with assertion in /SCMTMS/CL_TOR_A_UPDATE_ITEMTRCP Action executed from the BOPF test UI (KBA 2104015) ST22; test from code or the standard UI instead
Action fails for one FU, works later FU locked by a planner in the cockpit SM12 for the lock entry

The company code check lives in SPRO → Transportation Management → Freight Order Management → Freight Order → Define Freight Order Types. The procuring company code on the freight order is derived from the company code assigned to the purchasing organization in the organization model. If freight units from several company codes share a truck, the Z program has to group by company code too.

5) Choosing the right interface for creation plus assignment

Option Fits when Watch out for
ADD_FU_BY_FUID in a Z report You have FO and FU numbers and run in the TM system Stage matching; one save per freight order
ADD_FUSTAGE_WITH_PLANNING You work with stage keys, or with container and package unit stages Parameter structure differs; read it in /BOBF/CONF_UI
TransportationOrderGenericRequest_In An external system sends the freight order as a message Before S/4HANA 2020 FU assignment needs the BAdI /SCMTMS/TOR_SE_TOR_GN_REQ; KBA 2875534
Public Cloud API “Assign Freight Unit to Freight Order” S/4HANA Cloud Public Edition, no custom ABAP on TOR Assigned FU sequence may differ from the intended one (KBA 3600901)

For the message route on older releases, the enhancement that the community uses implements method CHANGE_MODIFICATION of /SCMTMS/TOR_SE_TOR_GN_REQ and calls ADD_FUSTAGE_WITH_PLANNING there, after the standard has built the freight order. The undo operation for any of these is the root action REMOVE_STAGE_ASSIGNMENT; wire it into the same Z tool so a wrong upload can be reversed.

6) Mass processing: one LUW per freight order

For mass assignment there is no standard report that reads “freight order X gets freight units A, B, C” from a file. The structure of the standard background report /SCMTMS/TOR_FO_PROC_BATCH (transaction /SCMTMS/TOR_FO_PROC on S/4HANA) is a good model, and so is one of its known weaknesses: KBA 2300499 describes batch runs that save nothing when a single document fails. Avoid that by giving every freight order its own unit of work.

  1. Read the input and group it by freight order. Inside each group, sort freight units by source and destination so mismatches show up before the action call.
  2. Convert all freight order IDs to keys with one CONVERT_ALTERN_KEY call.
  3. For each freight order: one DO_ACTION with all its freight units, then SAVE if clean, otherwise CLEANUP.
  4. Write one result line per freight order (and the message texts) to an application log you can open in SLG1.
  5. Run as a background job. If you parallelize, split by freight order and make sure no freight unit appears in two packages, or the second package fails on the lock.

A worked example: an upload with 46 freight units for 4 trucks. Truck 1 gets 12 freight units to the same customer, so one action call links all 12. Truck 2 has 11 freight units, but 3 carry a different destination: expect 8 linked and 3 left unplanned. A report that only reads ET_FAILED_KEY counts all 11 as assigned. Compare the requested IDs with what is linked after the save.

7) Calling it from a RAP action

When a Fiori app with a RAP backend triggers the creation, the BOPF save collides with the RAP transaction model. The BOPF transaction manager registers its update task and issues COMMIT WORK. RAP owns the LUW and rejects that statement inside behavior code with the runtime error BEHAVIOR_ILLEGAL_STATEMENT.

Decouple instead. The RAP action validates the input, stores a request entry and schedules a background operation through bgPF: get the process from CL_BGMC_PROCESS_FACTORY=>GET_DEFAULT( ), hand it a class implementing IF_BGMC_OP_SINGLE, and call SAVE_FOR_EXECUTION( ) in the save sequence. The operation class then runs the same code as section 3 in its own LUW, where the BOPF save is allowed. The user gets a request ID immediately and sees the result once the operation has finished.

8) How to test it

  1. Create two freight units with the same source and destination and one with a different destination. Expected: three unplanned FUs in the freight unit worklist.
  2. Create the freight order through your factory call and save. Expected: an FO with the right TOR_TYPE and an empty freight unit list.
  3. Run the report with all three FU IDs. Expected: two FUs linked, the third remains unplanned (the behaviour reported for destination mismatches; verify in your release). If your report shows three as successful, the result check is wrong.
  4. Lock one FU by opening it in change mode in another session and rerun. Expected: error message, CLEANUP executed, nothing saved; SM12 shows the lock held by the other session.
  5. Do not use /BOBF/TEST_UI for the action itself because of the dump in KBA 2104015. Use it to inspect the FO root and stops after the save.

Takeaways

  • Creating a freight order and assigning freight units are two separate steps on /SCMTMS/TOR: CREATE_TOR_TOUR builds an empty FO, ADD_FU_BY_FUID or ADD_FUSTAGE_WITH_PLANNING links the freight unit stages.
  • An empty ET_FAILED_KEY does not prove the assignment happened. Check the stages and read back what was linked.
  • Save and clean up per freight order, so one bad document does not stop the batch.
  • From RAP, move the BOPF save into a bgPF operation instead of fighting the commit rules.

Hit a different cause of silent assignment failures? Describe it in the comments.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *