Tuesday, March 19, 2019

Copying files between your desktop and SAP

If you need to move a number of files or just move files between SAP and your desktop on a regular basis then you're probably not very happy with using CG3Z and CG3Y. I wrote a program to allow you to drag-and-drop files using just your mouse

On the selection screen you can enter starting paths for the PC and the server saving you time clicking around. You can also limit the file selection to just files you're interested in e.g. *.txt to get just text files.

The program uses a pair of CL_GUI_ALV_TREE controls sitting inside a splitter. You will need to create a screen with a huge custom control on it called MAINCONT.

*&---------------------------------------------------------------------*
*& Report  ZZFILE
*&
*&---------------------------------------------------------------------*
*& File manager to move and copy files
*& Mark Langenhoven
*& 2019/02/14
*&---------------------------------------------------------------------*

report zzfile.

*--- Class deferring ------------------------------------------------
class lcl_tree_eventhandler definition deferred.


*--- Constants ------------------------------------------------------
constants: gc_windows(10) value 'WINDOWS',
           gc_unix(4)     value 'UNIX'.


*--- Types ----------------------------------------------------------
types: begin of t_file,
         dirname  type char600,
         name     type char300,
         type_id  type char1,
         type     type char40,
         len(16)  type p,
         owner    type char8,
         mtime(6) type p,
         mode     type char9,
         useable  type char1,
         subrc    type char4,
         errno    type char3,
         errmsg   type char40,
         mod_date type d,
         mod_time type char8,
         seen     type char1,
         changed  type char1,
         checked  type c,
       end of t_file.

data: begin of ls_tree,
        directory(10) type c,
        filename(10)  type c,
        len(16)       type p,
        date          like sy-datum,
        time          like sy-uzeit,
      end of ls_tree.

types: begin of tree_type,
         parent_node type lvc_nkey,
         node_key    type lvc_nkey,
         name        type string,
         filetype    type c,
       end of tree_type.


*--- Data declarations ----------------------------------------------
data: the_handler type ref to lcl_tree_eventhandler, "application,
      custom      type ref to cl_gui_custom_container,
      v_split     type ref to cl_gui_splitter_container,
      l_tree_con  type ref to cl_gui_container,
      r_tree_con  type ref to cl_gui_container,
      server_tree type ref to cl_gui_alv_tree,
      pc_tree     type ref to cl_gui_alv_tree.

data: g_event(30),
      g_node_key type lvc_nkey.

data: okcode    like sy-ucomm,
      firsttime.

data: gv_servtype(10),
      gv_pctype(10).

data: gv_servdir      type string,
      gv_pcdir        type string,
      gv_serv_changed,
      gv_pc_changed.

data: gs_file      type t_file,
      gt_servfiles type standard table of t_file,
      gt_pcfiles   type standard table of t_file.

data: gt_tree     like standard table of ls_tree,
      gt_fieldcat type lvc_t_fcat.

data: gt_serv_tree type standard table of tree_type,
      gt_pc_tree   type standard table of tree_type,
      gs_tree      type tree_type.

data: gv_serv_dragdrop type ref to cl_dragdrop,
      gv_pc_dragdrop   type ref to cl_dragdrop,
      gv_serv_handle   type i,
      gv_pc_handle     type i.

data: gv_answer    type c,
      gv_stop_copy type c,
      gv_overwrite type c.



*--- Class implementations -----------------------------------------
class lcl_dragdropobj definition.
  public section.
    data: node_keys type lvc_t_nkey.
endclass.



class lcl_tree_eventhandler definition.
  public section.
    methods:
      l_no_children
      for event expand_nc
                    of cl_gui_alv_tree
        importing node_key,

      l_double
      for event node_double_click
                    of cl_gui_alv_tree
        importing node_key,

      l_ondrag
      for event on_drag_multiple
            of cl_gui_alv_tree
        importing
            sender
            drag_drop_object
            fieldname
            node_key_table,

      l_ondrop
      for event on_drop
            of cl_gui_alv_tree
        importing
            drag_drop_object
            node_key,






      r_no_children
      for event expand_nc
                    of cl_gui_alv_tree
        importing node_key,

      r_double
      for event node_double_click
                    of cl_gui_alv_tree
        importing node_key,

      r_ondrag
      for event on_drag_multiple
            of cl_gui_alv_tree
        importing
            drag_drop_object
            fieldname
            node_key_table,

      r_ondrop
      for event on_drop
            of cl_gui_alv_tree
        importing
            sender
            drag_drop_object
            node_key.

endclass.



class lcl_tree_eventhandler implementation.

  "--- SERVER events --------------------------------------
  method l_no_children.

    data: lv_path type string.

    g_node_key = node_key.

    "Build up the path, so that we can add additional nodes in under here
    clear lv_path.
    do.
      read table gt_serv_tree into gs_tree with key node_key = g_node_key.
      perform build_path using gs_tree-name gv_servtype abap_false changing lv_path.

      g_node_key = gs_tree-parent_node.
      if g_node_key is initial.
        exit.
      endif.
    enddo.

    perform add_server_files using node_key lv_path.

  endmethod.


  "Refresh the current directory
  method l_double.

    data: lv_path type string.

    g_node_key = node_key.
    read table gt_serv_tree into gs_tree with key node_key = g_node_key.
    check gs_tree-filetype = 'd'.

    loop at gt_serv_tree into gs_tree where parent_node = g_node_key.
      call method server_tree->delete_subtree
        exporting
          i_node_key            = gs_tree-node_key
        exceptions
          node_key_not_in_model = 1
          others                = 2.
      if sy-subrc <> 0.
*       Implement suitable error handling here
      endif.

      delete gt_serv_tree.
    endloop.

    "Build up the path, so that we can add additional nodes in under here
    clear lv_path.
    do.
      read table gt_serv_tree into gs_tree with key node_key = g_node_key.
      perform build_path using gs_tree-name gv_servtype abap_false changing lv_path.

      g_node_key = gs_tree-parent_node.
      if g_node_key is initial.
        exit.
      endif.
    enddo.

    perform add_server_files using node_key lv_path.

  endmethod.



  method l_ondrag.

    data: dataobj type ref to lcl_dragdropobj.

    create object dataobj.

    refresh dataobj->node_keys.
    append lines of node_key_table to dataobj->node_keys.

    "If you don't fill this object references, the drop event
    "is never fired
    drag_drop_object->object = dataobj.
  endmethod.



  method l_ondrop.

    data: dataobj     type ref to lcl_dragdropobj,
          ls_node     type lvc_nkey,
          lv_movetype,
          lv_num      type i,
          lv_perc     type i.

    catch system-exceptions move_cast_error = 1.

      dataobj ?= drag_drop_object->object.

      if drag_drop_object->effect = cl_dragdrop=>copy.
        lv_movetype = 'C'.
      else.
        lv_movetype = 'M'.
      endif.


      clear gv_answer.
      describe table dataobj->node_keys lines lv_num.

      loop at dataobj->node_keys into ls_node.
        lv_perc = sy-tabix * 100 / lv_num.
        read table gt_pc_tree into gs_tree with key node_key = ls_node.
        call function 'SAPGUI_PROGRESS_INDICATOR'
          exporting
            percentage = lv_perc
            text       = gs_tree-name.


        perform copy2serv using ls_node node_key lv_movetype.
      endloop.

    endcatch.
    if sy-subrc <> 0.
      call method drag_drop_object->abort.
    endif.

    call method pc_tree->frontend_update.
    call method server_tree->frontend_update.

    message s000(38) with lv_num 'files completed'.
  endmethod.




  "--- PC events ------------------------------------------
  method r_no_children.

    data: lv_path type string.

    g_node_key = node_key.
    clear lv_path.
    do.
      read table gt_pc_tree into gs_tree with key node_key = g_node_key.
      perform build_path using gs_tree-name gv_pctype abap_false changing lv_path.

      g_node_key = gs_tree-parent_node.
      if g_node_key is initial.
        exit.
      endif.
    enddo.


    perform add_pc_files using node_key lv_path.
  endmethod.


  "Refresh the current directory
  method r_double.

    data: lv_path type string.

    g_node_key = node_key.
    "Only operate on directories
    read table gt_pc_tree into gs_tree with key node_key = g_node_key.
    check gs_tree-filetype = 'd'.

    "Wipe out all the file nodes in this directory
    loop at gt_pc_tree into gs_tree where parent_node = g_node_key.
      call method pc_tree->delete_subtree
        exporting
          i_node_key            = gs_tree-node_key
        exceptions
          node_key_not_in_model = 1
          others                = 2.
      if sy-subrc <> 0.
*       Implement suitable error handling here
      endif.

      delete gt_pc_tree.

    endloop.

    clear lv_path.
    do.
      read table gt_pc_tree into gs_tree with key node_key = g_node_key.
      perform build_path using gs_tree-name gv_pctype abap_false changing lv_path.

      g_node_key = gs_tree-parent_node.
      if g_node_key is initial.
        exit.
      endif.
    enddo.


    perform add_pc_files using node_key lv_path.


  endmethod.


  method r_ondrag.

    data: dataobj type ref to lcl_dragdropobj.

    create object dataobj.

    refresh dataobj->node_keys.
    append lines of node_key_table to dataobj->node_keys.

    "If you don't fill this object references, the drop event
    "is never fired
    drag_drop_object->object = dataobj.
  endmethod.



  method r_ondrop.

    data: dataobj     type ref to lcl_dragdropobj,
          ls_node     type lvc_nkey,
          lv_movetype,
          lv_num      type i,
          lv_perc     type i.


    catch system-exceptions move_cast_error = 1.

      dataobj ?= drag_drop_object->object.

      if drag_drop_object->effect = cl_dragdrop=>copy.
        lv_movetype = 'C'.
      else.
        lv_movetype = 'M'.
      endif.

      clear gv_answer.
      describe table dataobj->node_keys lines lv_num.


      loop at dataobj->node_keys into ls_node.
        lv_perc = sy-tabix * 100 / lv_num.
        read table gt_serv_tree into gs_tree with key node_key = ls_node.
        call function 'SAPGUI_PROGRESS_INDICATOR'
          exporting
            percentage = lv_perc
            text       = gs_tree-name.


        perform copy2pc using ls_node node_key lv_movetype.
      endloop.

    endcatch.
    if sy-subrc <> 0.
      call method drag_drop_object->abort.
    endif.

    call method pc_tree->frontend_update.
    call method server_tree->frontend_update.

    message s000(38) with lv_num 'files completed'.
  endmethod.



endclass.






*--- Selection screen -----------------------------------------------
selection-screen begin of line.
selection-screen comment 1(25) ppc.
parameters: p_pc   type string obligatory default 'C:\Users\' lower case.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(25) pserv.
parameters: p_serv type string obligatory lower case.
selection-screen end of line.

selection-screen skip.
selection-screen begin of line.
selection-screen comment 1(25) pmask.
parameters: p_mask type string lower case.
selection-screen end of line.

selection-screen skip.
selection-screen begin of line.
parameters: p_saplft as checkbox default 'X'.
selection-screen comment 3(25) psaplft.
selection-screen end of line.

at selection-screen on value-request for p_pc.
  call method cl_gui_frontend_services=>directory_browse
    exporting
      window_title         = 'Select a PC directory'
      initial_folder       = p_pc
    changing
      selected_folder      = p_pc
    exceptions
      cntl_error           = 1
      error_no_gui         = 2
      not_supported_by_gui = 3
      others               = 4.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

at selection-screen on value-request for p_serv.
  call function '/SAPDMC/LSM_F4_SERVER_FILE'
    exporting
      directory        = p_serv
      filemask         = '?' "Bad filemask so we only show directories
    importing
      serverfile       = p_serv
    exceptions
      canceled_by_user = 1
      others           = 2.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.


initialization.
  ppc = 'PC Directory'.
  pserv = 'Server Directory'.
  pmask = 'File mask (e.g. *.txt)'.
  psaplft = 'SAP files on the left'.

  concatenate '/tmp/' sy-sysid into p_serv.


*=== Main program ===================================================
start-of-selection.

  perform init_systems.

  call screen  0100


*&---------------------------------------------------------------------*
*&      Form  CREATE_CONTAINERS
*&---------------------------------------------------------------------*
* Create all the containers on the screen
*----------------------------------------------------------------------*
form create_containers .

  data: events type cntl_simple_events,
        event  type cntl_simple_event.

  data: dragtypes type i.

  data: ls_fcat type lvc_s_fcat.




  check firsttime = abap_true.
  clear firsttime.


  "Field catalog for the additional fields on both sides
  clear ls_fcat.
  ls_fcat-fieldname = 'DATE'.
  ls_fcat-outputlen = 12.
  ls_fcat-scrtext_s = 'Date'.
  ls_fcat-ref_field = 'DATUM'.
  ls_fcat-ref_table = 'SYST'.
  append ls_fcat to gt_fieldcat.

  clear ls_fcat.
  ls_fcat-fieldname = 'TIME'.
  ls_fcat-outputlen = 10.
  ls_fcat-scrtext_s = 'Time'.
  ls_fcat-ref_field = 'UZEIT'.
  ls_fcat-ref_table = 'SYST'.
  append ls_fcat to gt_fieldcat.

  clear ls_fcat.
  ls_fcat-fieldname = 'LEN'.
  ls_fcat-outputlen = 10.
  ls_fcat-scrtext_s = 'Size'.
  append ls_fcat to gt_fieldcat.



  create object the_handler.

  "Create a screen with a huge custom container and allow it
  "to resize as small as it wants
  create object custom
    exporting
      container_name              = 'MAINCONT'
    exceptions
      cntl_error                  = 1
      cntl_system_error           = 2
      create_error                = 3
      lifetime_error              = 4
      lifetime_dynpro_dynpro_link = 5
      others                      = 6.
  if sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
  endif.

  "Split the screen in half vertically
  create object v_split
    exporting
      parent  = custom
      rows    = 1
      columns = 2.

  "Split each half in half again horizontally
  call method v_split->get_container
    exporting
      row       = 1
      column    = 1
    receiving
      container = l_tree_con.


  call method v_split->get_container
    exporting
      row       = 1
      column    = 2
    receiving
      container = r_tree_con.





  "Create the SERVER tree
  if p_saplft = abap_true.
    create object server_tree
      exporting
        parent                      = l_tree_con
        node_selection_mode         = cl_tree_control_base=>node_sel_mode_multiple
        no_html_header              = abap_true
        no_toolbar                  = abap_true
      exceptions
        cntl_error                  = 1
        cntl_system_error           = 2
        create_error                = 3
        lifetime_error              = 4
        illegal_node_selection_mode = 5
        failed                      = 6
        illegal_column_name         = 7
        others                      = 8.
    if sy-subrc <> 0.
*   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
  else.
    create object server_tree
      exporting
        parent                      = r_tree_con
        node_selection_mode         = cl_tree_control_base=>node_sel_mode_multiple
        no_html_header              = abap_true
        no_toolbar                  = abap_true
      exceptions
        cntl_error                  = 1
        cntl_system_error           = 2
        create_error                = 3
        lifetime_error              = 4
        illegal_node_selection_mode = 5
        failed                      = 6
        illegal_column_name         = 7
        others                      = 8.
    if sy-subrc <> 0.
*   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
  endif.



  call method server_tree->get_registered_events
    importing
      events     = events
    exceptions
      cntl_error = 1
      others     = 2.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  "Set the event handlers for the server
  event-eventid = cl_gui_column_tree=>eventid_node_double_click.
  append event to events.
  event-eventid = cl_gui_column_tree=>eventid_expand_no_children.
  append event to events.

  call method server_tree->set_registered_events
    exporting
      events                    = events
    exceptions
      cntl_error                = 1
      cntl_system_error         = 2
      illegal_event_combination = 3
      others                    = 4.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  set handler the_handler->l_no_children for server_tree.
  set handler the_handler->l_ondrag for server_tree.
  set handler the_handler->l_ondrop for server_tree.
  set handler the_handler->l_double for server_tree.


  create object gv_serv_dragdrop.

  dragtypes = cl_dragdrop=>move + cl_dragdrop=>copy.

  call method gv_serv_dragdrop->add
    exporting
      flavor          = 'SERV2PC'
      dragsrc         = abap_true
      droptarget      = space
      effect          = dragtypes
    exceptions
      already_defined = 1
      obj_invalid     = 2
      others          = 3.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  call method gv_serv_dragdrop->add
    exporting
      flavor          = 'PC2SERV'
      dragsrc         = space
      droptarget      = abap_true
      effect          = dragtypes
    exceptions
      already_defined = 1
      obj_invalid     = 2
      others          = 3.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  call method gv_serv_dragdrop->get_handle
    importing
      handle      = gv_serv_handle
    exceptions
      obj_invalid = 1
      others      = 2.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  perform build_server_tree.






  "Create the PC tree
  if p_saplft = abap_true.
    create object pc_tree
      exporting
        parent                      = r_tree_con
        node_selection_mode         = cl_tree_control_base=>node_sel_mode_multiple
        no_toolbar                  = abap_true
        no_html_header              = abap_true
      exceptions
        cntl_error                  = 1
        cntl_system_error           = 2
        create_error                = 3
        lifetime_error              = 4
        illegal_node_selection_mode = 5
        failed                      = 6
        illegal_column_name         = 7
        others                      = 8.
    if sy-subrc <> 0.
*   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.

  else.
    create object pc_tree
      exporting
        parent                      = l_tree_con
        node_selection_mode         = cl_tree_control_base=>node_sel_mode_multiple
        no_toolbar                  = abap_true
        no_html_header              = abap_true
      exceptions
        cntl_error                  = 1
        cntl_system_error           = 2
        create_error                = 3
        lifetime_error              = 4
        illegal_node_selection_mode = 5
        failed                      = 6
        illegal_column_name         = 7
        others                      = 8.
    if sy-subrc <> 0.
*   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
  endif.


  refresh events.

  call method pc_tree->get_registered_events
    importing
      events     = events
    exceptions
      cntl_error = 1
      others     = 2.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.


  "Set the event handlers for the PC
  event-eventid = cl_gui_column_tree=>eventid_node_double_click.
  append event to events.
  event-eventid = cl_gui_column_tree=>eventid_expand_no_children.
  append event to events.


  call method pc_tree->set_registered_events
    exporting
      events                    = events
    exceptions
      cntl_error                = 1
      cntl_system_error         = 2
      illegal_event_combination = 3
      others                    = 4.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  set handler the_handler->r_no_children for pc_tree.
  set handler the_handler->r_ondrag for pc_tree.
  set handler the_handler->r_ondrop for pc_tree.
  set handler the_handler->r_double for pc_tree.

  create object gv_pc_dragdrop.

  dragtypes = cl_dragdrop=>move + cl_dragdrop=>copy.

  call method gv_pc_dragdrop->add
    exporting
      flavor          = 'SERV2PC'
      dragsrc         = space
      droptarget      = abap_true
      effect          = dragtypes
    exceptions
      already_defined = 1
      obj_invalid     = 2
      others          = 3.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  call method gv_pc_dragdrop->add
    exporting
      flavor          = 'PC2SERV'
      dragsrc         = abap_true
      droptarget      = space
      effect          = dragtypes
    exceptions
      already_defined = 1
      obj_invalid     = 2
      others          = 3.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  call method gv_pc_dragdrop->get_handle
    importing
      handle      = gv_pc_handle
    exceptions
      obj_invalid = 1
      others      = 2.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  perform build_pc_tree.

endform.


*&---------------------------------------------------------------------*
*&      Form  BUILD_SERVER_TREE
*&---------------------------------------------------------------------*
* Using the supplied path as the starting point, build up a tree of the
* subdirectories below it
*----------------------------------------------------------------------*
form build_server_tree.

  data: ls_layout         type lvc_s_layn,
        lv_relat_node_key type lvc_nkey,
        lv_main_key       type lvc_nkey,
        ls_head           type treev_hhdr,
        lv_value          type lvc_value.



  ls_head-heading = 'Files on server'.
  ls_head-width = 50.
  ls_head-width_pix = ''.

  call method server_tree->set_table_for_first_display
    exporting
      is_hierarchy_header = ls_head
    changing
      it_outtab           = gt_tree
      it_fieldcatalog     = gt_fieldcat.


  ls_layout-isfolder = abap_true.
  ls_layout-expander = abap_true.
  ls_layout-dragdropid = gv_serv_handle.


  clear ls_tree.
  lv_value = p_serv.
  call method server_tree->add_node
    exporting
      i_relat_node_key     = lv_relat_node_key
      i_relationship       = cl_tree_control_base=>relat_last_child
      is_outtab_line       = ls_tree
      is_node_layout       = ls_layout
      i_node_text          = lv_value
    importing
      e_new_node_key       = lv_main_key
    exceptions
      relat_node_not_found = 1
      node_not_found       = 2
      others               = 3.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.

  refresh gt_serv_tree.

  perform build_my_tree tables gt_serv_tree using lv_relat_node_key lv_main_key p_serv 'd'.

  perform add_server_files using lv_main_key gv_servdir.

endform.


*&---------------------------------------------------------------------*
*&      Module  STATUS_0100  OUTPUT
*&---------------------------------------------------------------------*
module status_0100 output.

  data: lv_mask type string.
  set pf-status 'MAIN0100'.

  clear lv_mask.
  if p_mask is not initial.
    concatenate '- (' p_mask ')' into lv_mask.
  endif.
  set titlebar 'FIL' with lv_mask.

  perform create_containers.

endmodule.


*&---------------------------------------------------------------------*
*&      Module  USER_COMMAND_0100  INPUT
*&---------------------------------------------------------------------*
module user_command_0100 input.

  if sy-ucomm = 'E'.
    leave to screen 0.
  endif.

  call method cl_gui_cfw=>dispatch.
endmodule.


*&---------------------------------------------------------------------*
*&      Form  INIT_SYSTEMS
*&---------------------------------------------------------------------*
* Initialise the directories and operating systems
*----------------------------------------------------------------------*
form init_systems .

  data: lv_platform type i.


  firsttime = abap_true.


  "Determine the operating system of the server
  if sy-opsys cs 'Windows'.
    gv_servtype = gc_windows.
  else.
    gv_servtype = gc_unix.
  endif.

  "Determine the starting directory for the server
  if p_serv is initial.
    if gv_servtype = gc_unix.
      gv_servdir = '/'.
    else.
      gv_servdir = 'C:\'.
    endif.
  else.
    gv_servdir = p_serv.
  endif.

  "Check that this is a valid starting directory
  if gv_servtype = gc_unix.
    if gv_servdir cs '\'.
      message e000(38) with 'Invalid directory specified' 'Only Unix paths are accepted'.
      exit.
    endif.
  else.
    if gv_servdir cs '/'.
      message e000(38) with 'Invalid directory specified' 'Only Windows paths are accepted'.
      exit.
    endif.
  endif.


  "Determine the operating system of the PC
  call method cl_gui_frontend_services=>get_platform
    receiving
      platform             = lv_platform
    exceptions
      error_no_gui         = 1
      cntl_error           = 2
      not_supported_by_gui = 3
      others               = 4.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  if lv_platform = cl_gui_frontend_services=>platform_windowsxp.
    gv_pctype = gc_windows.
  else.
    gv_pctype = gc_unix.
    message e000(38) with 'I do not support Unix frontends at the moment'.
  endif.


  "Determine the starting directory for the PC
  if p_pc is initial.
    if gv_pctype = gc_unix.
      gv_pcdir = '/'.
    else.
      gv_pcdir = 'C:\'.
    endif.
  else.
    gv_pcdir = p_pc.
  endif.

  "Check that this is a valid starting directory
  if gv_pctype = gc_unix.
    if gv_pcdir cs '\'.
      message e000(38) with 'Invalid directory specified' 'Only Unix paths are accepted'.
      exit.
    endif.
  else.
    if gv_pcdir cs '/'.
      message e000(38) with 'Invalid directory specified' 'Only Windows paths are accepted'.
      exit.
    endif.
  endif.


  "Mark both systems as changed initially so we can get the starting
  "direcotry information
  gv_serv_changed = abap_true.
  gv_pc_changed = abap_true.
endform.



*&---------------------------------------------------------------------*
*&      Form  GET_SERV_FILES
*&---------------------------------------------------------------------*
* Find all the files and directories below the current directory
*----------------------------------------------------------------------*
form get_serv_files  tables   pt_files structure gs_file
                     using pv_dir.

  constants: c_dir    type char10 value 'DIR',
             c_file   type char10 value 'FILE',
             c_name   type char10 value 'NAME',
             c_owner  type char10 value 'OWNER',
             c_len    type char10 value 'LEN',
             c_mode   type char10 value 'MODE',
             c_mtime  type char10 value 'MTIME',
             c_type   type char10 value 'TYPE',
             c_errmsg type char10 value 'ERRMSG',
             c_errno  type char10 value 'ERRNO'.

  data: lv_path_name type localfile,
        lv_file_name type localfile.

  data: ls_file   type t_file,
        ctime(10) type c,
        time      like sy-uzeit,
        date      like sy-datum.


  refresh pt_files.

  lv_path_name = pv_dir.

* End of directory read (initialize the next call)
  call 'C_DIR_READ_FINISH' id c_errno field ls_file-errno
                           id c_errmsg field ls_file-errmsg.

  call 'C_DIR_READ_START' id c_dir field lv_path_name
                        id c_file field lv_file_name
                        id c_errno field ls_file-errno
                        id c_errmsg field ls_file-errmsg.

  if sy-subrc <> 0.
    message e000(38) with 'Error reading directory' gv_servdir ls_file-errmsg.
  else.

    do.
      call 'C_DIR_READ_NEXT'
         id c_type field ls_file-type
         id c_name field ls_file-name
         id c_len field ls_file-len
         id c_owner field ls_file-owner
         id c_mtime field ls_file-mtime
         id c_mode field ls_file-mode
         id c_errno field ls_file-errno
         id c_errmsg field ls_file-errmsg.

      ls_file-dirname = gv_servdir.
      ls_file-subrc = sy-subrc.
      translate ls_file-type to lower case.


      case sy-subrc.

          "Determine if a file is useable or not
        when 0.

          if ls_file-type(1) = 'f' or
             ls_file-type(1) = 'd'.
            "Add to the list of files to display
            if ls_file-mode(1) >= '5'.
              ls_file-useable = 'W'. "File or dir is writeable
            elseif ls_file-mode(1) = '4'.
              ls_file-useable = 'R'. "Only read permissions
            else.
              clear ls_file-useable. "No permissions
            endif.

            perform p6_to_date_time_tz(rstr0400) using ls_file-mtime
                                           ctime
                                           date.
            translate ctime using ': '.
            condense ctime no-gaps.
            time = ctime.
            ls_file-mod_date = date.
            ls_file-mod_time = time.
            append ls_file to pt_files.
          endif.


        when 1.
          exit.
        when others.
      endcase.

    enddo.

  endif.

  sort pt_files by name.

endform.


*&---------------------------------------------------------------------*
*&      Form  BUILD_MY_TREE
*&---------------------------------------------------------------------*
* Build my internal version of the tree to keep track of sub-directories
* and file locations
*----------------------------------------------------------------------*
form build_my_tree  tables   pt_tree structure gs_tree
                    using    pv_header_node
                             pv_node
                             pv_name
                             value(pv_type).

  clear gs_tree.
  gs_tree-parent_node = pv_header_node.
  gs_tree-node_key = pv_node.
  gs_tree-name = pv_name.
  gs_tree-filetype = pv_type.
  append gs_tree to pt_tree.


endform.


*&---------------------------------------------------------------------*
*&      Form  BUILD_PATH
*&---------------------------------------------------------------------*
* Build up the path based on the OS type
*----------------------------------------------------------------------*
form build_path  using    pv_dir_name
                          pv_ostype
                          pv_file
                 changing pv_path.

  data: separator type c.

  if pv_ostype = gc_windows.
    separator = '\'.
  else.
    separator = '/'.
  endif.

  if pv_file = abap_true and pv_path is initial.
    clear separator.
  endif.

  concatenate pv_dir_name separator pv_path into pv_path.

  "If the user added a slash to the end of the starting paths
  "then we could end up with duplicated separators
  replace all occurrences of '\\' in pv_path with '\'.
  replace all occurrences of '//' in pv_path with '/'.

endform.


*&---------------------------------------------------------------------*
*&      Form  ADD_SERVER_FILES
*&---------------------------------------------------------------------*
* Add files to the specified node for the supplied path
*----------------------------------------------------------------------*
form add_server_files  using    pv_node
                                pv_path.

  data: lv_name           type lvc_value,
        ls_layout         type lvc_s_layn,
        lv_relat_node_key type lvc_nkey,
        lv_matched        type c.



  perform get_serv_files tables gt_servfiles using pv_path.



  "First add any sub-directories
  loop at gt_servfiles into gs_file where type(1) = 'd'.

    lv_name = gs_file-name.
    check lv_name <> '.' and
          lv_name <> '..'.

    clear ls_layout.
    if gs_file-useable = 'W'.
      ls_layout-isfolder = abap_true.
      ls_layout-expander = abap_true.
      ls_layout-dragdropid = gv_serv_handle.
    endif.
    if gs_file-useable = 'R'.
      ls_layout-isfolder = abap_true.
      ls_layout-expander = abap_true.
    endif.
    if gs_file-useable = abap_false.
      ls_layout-isfolder = abap_true.
      ls_layout-disabled = abap_true.
    endif.

    clear ls_tree.
    ls_tree-date = gs_file-mod_date.
    ls_tree-time = gs_file-mod_time.
    clear ls_tree-len.

    call method server_tree->add_node
      exporting
        i_relat_node_key     = pv_node
        i_relationship       = cl_tree_control_base=>relat_last_child
        is_outtab_line       = ls_tree
        is_node_layout       = ls_layout
        i_node_text          = lv_name
      importing
        e_new_node_key       = lv_relat_node_key
      exceptions
        relat_node_not_found = 1
        node_not_found       = 2
        others               = 3.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    perform build_my_tree tables gt_serv_tree using pv_node lv_relat_node_key  gs_file-name gs_file-type(1).

  endloop.



  "Add the files
  loop at gt_servfiles into gs_file where type(1) = 'f'.

    "If there's a mask filter in place, then see if this file matches it
    perform match_mask using gs_file-name changing lv_matched.
    check lv_matched = abap_true.

    lv_name = gs_file-name.

    clear ls_layout.
    if gs_file-useable = 'W'.
      ls_layout-dragdropid = gv_serv_handle.
    else.
      ls_layout-disabled = abap_true.
    endif.

    clear ls_tree.
    ls_tree-date = gs_file-mod_date.
    ls_tree-time = gs_file-mod_time.
    ls_tree-len = gs_file-len.

    call method server_tree->add_node
      exporting
        i_relat_node_key     = pv_node
        i_relationship       = cl_tree_control_base=>relat_last_child
        is_outtab_line       = ls_tree
        is_node_layout       = ls_layout
        i_node_text          = lv_name
      importing
        e_new_node_key       = lv_relat_node_key
      exceptions
        relat_node_not_found = 1
        node_not_found       = 2
        others               = 3.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    perform build_my_tree tables gt_serv_tree using pv_node lv_relat_node_key  gs_file-name gs_file-type(1).

  endloop.



  call method server_tree->expand_node
    exporting
      i_node_key          = pv_node
    exceptions
      failed              = 1
      illegal_level_count = 2
      cntl_system_error   = 3
      node_not_found      = 4
      cannot_expand_leaf  = 5
      others              = 6.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.


  call method server_tree->frontend_update.


endform.


*&---------------------------------------------------------------------*
*&      Form  BUILD_PC_TREE
*&---------------------------------------------------------------------*
* Build up the tree containing the PC folders and files
*----------------------------------------------------------------------*
form build_pc_tree.

  data: ls_layout         type lvc_s_layn,
        lv_relat_node_key type lvc_nkey,
        lv_main_key       type lvc_nkey,
        ls_head           type treev_hhdr,
        ls_fcat           type lvc_s_fcat,
        lv_value          type lvc_value.



  ls_head-heading = 'Files on PC'.
  ls_head-width = 50.
  ls_head-width_pix = ''.

  call method pc_tree->set_table_for_first_display
    exporting
      is_hierarchy_header = ls_head
    changing
      it_outtab           = gt_tree
      it_fieldcatalog     = gt_fieldcat.

  ls_layout-isfolder = abap_true.
  ls_layout-expander = abap_true.
  ls_layout-dragdropid = gv_pc_handle.

  clear ls_tree.
  lv_value = p_pc.
  call method pc_tree->add_node
    exporting
      i_relat_node_key     = lv_relat_node_key
      i_relationship       = cl_tree_control_base=>relat_last_child
      is_outtab_line       = ls_tree
      is_node_layout       = ls_layout
      i_node_text          = lv_value
    importing
      e_new_node_key       = lv_main_key
    exceptions
      relat_node_not_found = 1
      node_not_found       = 2
      others               = 3.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.

  refresh gt_pc_tree.

  perform build_my_tree tables gt_pc_tree using lv_relat_node_key lv_main_key p_pc 'd'.

  perform add_pc_files using lv_main_key p_pc.
endform.


*&---------------------------------------------------------------------*
*&      Form  ADD_PC_FILES
*&---------------------------------------------------------------------*
* Add the folders and files found on the PC
*----------------------------------------------------------------------*
form add_pc_files  using    pv_node
                            pv_path.


  data: lv_path           type string,
        ls_layout         type lvc_s_layn,
        lt_files          type standard table of file_info,
        ls_file           type file_info,
        lv_relat_node_key type lvc_nkey,
        lv_value          type lvc_value,
        lv_matched        type c,
        lv_count          type i.


  lv_path = pv_path.

  call method cl_gui_frontend_services=>directory_list_files
    exporting
      directory                   = lv_path
    changing
      file_table                  = lt_files
      count                       = lv_count
    exceptions
      cntl_error                  = 1
      directory_list_files_failed = 2
      wrong_parameter             = 3
      error_no_gui                = 4
      not_supported_by_gui        = 5
      others                      = 6.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.


  sort lt_files by filename.

  "First add all the sub-directories
  ls_layout-isfolder = abap_true.
  ls_layout-expander = abap_true.
  ls_layout-dragdropid = gv_pc_handle.

  loop at lt_files into ls_file where isdir = 1. "Insane moron using int for a flag
    check ls_file-ishidden = 0.

    clear ls_tree.
    ls_tree-date = ls_file-createdate.
    ls_tree-time = ls_file-createtime.

    lv_value = ls_file-filename.

    call method pc_tree->add_node
      exporting
        i_relat_node_key     = pv_node
        i_relationship       = cl_tree_control_base=>relat_last_child
        is_outtab_line       = ls_tree
        is_node_layout       = ls_layout
        i_node_text          = lv_value
      importing
        e_new_node_key       = lv_relat_node_key
      exceptions
        relat_node_not_found = 1
        node_not_found       = 2
        others               = 3.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    perform build_my_tree tables gt_pc_tree using  pv_node lv_relat_node_key ls_file-filename 'd'.

  endloop.

  "Now add all the files
  clear ls_layout.
  ls_layout-dragdropid = gv_pc_handle.


  loop at lt_files into ls_file where isdir = 0.
    check ls_file-ishidden = 0.
    clear ls_tree.
    lv_value = ls_file-filename.

    "If there's a mask filter in place, then see if this file matches it
    perform match_mask using ls_file-filename changing lv_matched.
    check lv_matched = abap_true.

    clear ls_tree.
    ls_tree-date = ls_file-createdate.
    ls_tree-time = ls_file-createtime.
    ls_tree-len = ls_file-filelength.

    call method pc_tree->add_node
      exporting
        i_relat_node_key     = pv_node
        i_relationship       = cl_tree_control_base=>relat_last_child
        is_outtab_line       = ls_tree
        is_node_layout       = ls_layout
        i_node_text          = lv_value
      importing
        e_new_node_key       = lv_relat_node_key
      exceptions
        relat_node_not_found = 1
        node_not_found       = 2
        others               = 3.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    perform build_my_tree tables gt_pc_tree using pv_node lv_relat_node_key ls_file-filename 'f'.

  endloop.


  call method pc_tree->expand_node
    exporting
      i_node_key          = pv_node
    exceptions
      failed              = 1
      illegal_level_count = 2
      cntl_system_error   = 3
      node_not_found      = 4
      cannot_expand_leaf  = 5
      others              = 6.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

  call method pc_tree->frontend_update.
endform.


*&---------------------------------------------------------------------*
*&      Form  COPY2PC
*&---------------------------------------------------------------------*
* Copy a file to the PC
*----------------------------------------------------------------------*
form copy2pc  using    pv_server_node
                       pv_pc_node
                       pv_move_type.

  data: lv_relat_node_key type lvc_nkey,
        lv_pc_node        type lvc_nkey,
        lv_value          type lvc_value,
        ls_layout         type lvc_s_layn,
        lv_file_name      type string.


  "If the PC destination is a file, then find the directory that it's in
  read table gt_pc_tree into gs_tree with key node_key = pv_pc_node.
  if gs_tree-filetype = 'f'.
    lv_pc_node = gs_tree-parent_node.
  else.
    lv_pc_node = pv_pc_node.
  endif.

  read table gt_serv_tree into gs_tree with key node_key = pv_server_node.
  check sy-subrc = 0.


  "If the SERVER origin is a directory, then copy all the files inside it
  if gs_tree-filetype = 'd'.
    "Loop through all the files in this directory and copy them over
    loop at gt_serv_tree into gs_tree where parent_node = pv_server_node.
      perform copy2pc using gs_tree-node_key lv_pc_node pv_move_type.
    endloop.

    exit.

  endif.


  "Copy the actual file -----------------------------------
  clear gv_stop_copy.
  perform file2pc using pv_server_node lv_pc_node pv_move_type changing lv_file_name.
  check gv_stop_copy is initial.



  if gv_overwrite is initial.
    "Add the node to the PC tree ----------------------------
    clear ls_tree.
    lv_value = lv_file_name.
    clear ls_layout.
    ls_layout-dragdropid = gv_pc_handle.

    call method pc_tree->add_node
      exporting
        i_relat_node_key     = lv_pc_node
        i_relationship       = cl_tree_control_base=>relat_last_child
        is_outtab_line       = ls_tree
        is_node_layout       = ls_layout
        i_node_text          = lv_value
      importing
        e_new_node_key       = lv_relat_node_key
      exceptions
        relat_node_not_found = 1
        node_not_found       = 2
        others               = 3.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    perform build_my_tree tables gt_pc_tree using lv_pc_node lv_relat_node_key lv_file_name 'f'.

  endif.


  "See if this was a move rather than a copy
  check pv_move_type = 'M'.


  "Remove the node from the SERVER tree -------------------
  call method server_tree->delete_subtree
    exporting
      i_node_key            = pv_server_node
    exceptions
      node_key_not_in_model = 1
      others                = 2.
  if sy-subrc <> 0.
*     Implement suitable error handling here
  endif.

  delete gt_serv_tree where node_key = pv_server_node.


endform.



*&---------------------------------------------------------------------*
*&      Form  COPY2SERV
*&---------------------------------------------------------------------*
* Copy files from the PC to the SERVER
*----------------------------------------------------------------------*
form copy2serv  using    pv_pc_node
                         pv_server_node
                         pv_move_type.

  data: lv_relat_node_key type lvc_nkey,
        lv_serv_node      type lvc_nkey,
        lv_value          type lvc_value,
        ls_layout         type lvc_s_layn,
        lv_file_name      type string.



  "If the SERVER destination is a file, then find the directory that it's in
  read table gt_serv_tree into gs_tree with key node_key = pv_server_node.
  if gs_tree-filetype = 'f'.
    lv_serv_node = gs_tree-parent_node.
  else.
    lv_serv_node = pv_server_node.
  endif.


  read table gt_pc_tree into gs_tree with key node_key = pv_pc_node.
  check sy-subrc = 0.


  "If the PC origin is a directory, then copy all the files inside it
  if gs_tree-filetype = 'd'.
    loop at gt_pc_tree into gs_tree where parent_node = pv_pc_node.
      perform copy2serv using gs_tree-node_key lv_serv_node pv_move_type.
    endloop.

    exit.

  endif.



  "Copy the actual file -----------------------------------
  clear gv_stop_copy.
  perform file2server using pv_pc_node lv_serv_node pv_move_type changing lv_file_name.
  check gv_stop_copy is initial.



  if gv_overwrite is initial.
    "Add the node to the SERVER tree ------------------------
    clear ls_tree.
    lv_value = lv_file_name.
    clear ls_layout.
    ls_layout-dragdropid = gv_serv_handle.

    call method server_tree->add_node
      exporting
        i_relat_node_key     = lv_serv_node
        i_relationship       = cl_tree_control_base=>relat_last_child
        is_outtab_line       = ls_tree
        is_node_layout       = ls_layout
        i_node_text          = lv_value
      importing
        e_new_node_key       = lv_relat_node_key
      exceptions
        relat_node_not_found = 1
        node_not_found       = 2
        others               = 3.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    perform build_my_tree tables gt_serv_tree using lv_serv_node lv_relat_node_key lv_file_name 'f'.

  endif.



  "See if this was a move rather than a copy
  check pv_move_type = 'M'.


  "Remove the node from the PC tree -----------------------
  call method pc_tree->delete_subtree
    exporting
      i_node_key            = pv_pc_node
    exceptions
      node_key_not_in_model = 1
      others                = 2.
  if sy-subrc <> 0.
*     Implement suitable error handling here
  endif.

  delete gt_pc_tree where node_key = pv_pc_node.


endform.


*&---------------------------------------------------------------------*
*&      Form  FILE2SERVER
*&---------------------------------------------------------------------*
* Copy a file to the server
*----------------------------------------------------------------------*
form file2server  using    pv_pc_node
                           pv_serv_node
                           pv_move_type
                  changing pv_file_name.


  data: lv_pc_name   type string,
        lv_serv_name type string,
        lv_file_size type i,
        lv_len       type i,
        lv_lines     type i,
        lt_data      type rcgrepfile occurs 0 with header line.



  g_node_key = pv_pc_node.
  clear lv_pc_name.
  do.
    read table gt_pc_tree into gs_tree with key node_key = g_node_key.
    if gs_tree-filetype = 'f'.
      pv_file_name = gs_tree-name.
    endif.

    perform build_path using gs_tree-name gv_pctype abap_true changing lv_pc_name.

    g_node_key = gs_tree-parent_node.
    if g_node_key is initial.
      exit.
    endif.
  enddo.


  g_node_key = pv_serv_node.
  clear lv_serv_name.
  do.
    read table gt_serv_tree into gs_tree with key node_key = g_node_key.
    perform build_path using gs_tree-name gv_servtype abap_false changing lv_serv_name.

    g_node_key = gs_tree-parent_node.
    if g_node_key is initial.
      exit.
    endif.
  enddo.

  concatenate lv_serv_name pv_file_name into lv_serv_name.

  clear: gv_stop_copy, gv_overwrite.


  "Check if the file already exists on the server
  if gv_answer is initial.
    open dataset lv_serv_name for input in binary mode.
    if sy-subrc = 0.
      call function 'POPUP_TO_CONFIRM'
        exporting
          titlebar              = 'File already exists'
          text_question         = lv_serv_name
          text_button_1         = 'Overwrite'
          text_button_2         = 'Overwrite ALL'
          default_button        = '3'
          display_cancel_button = 'X'
        importing
          answer                = gv_answer
        exceptions
          text_not_found        = 1
          others                = 2.
      if sy-subrc <> 0.
* Implement suitable error handling here
      endif.

      "Cancel the file copying
      if gv_answer = '3'.
        clear gv_answer.
        gv_stop_copy = abap_true.
        close dataset lv_serv_name.
        exit.
      endif.

      "Copy this file, but ask again next time
      if gv_answer = '1'.
        clear gv_answer.
        gv_overwrite = abap_true.
        close dataset lv_serv_name.
      endif.

    endif.
  endif.

  if gv_answer is not initial.
    gv_overwrite = abap_true.
  endif.

  check gv_stop_copy is initial.



  call function 'C13Z_UPLOAD'
    exporting
      filename                = lv_pc_name
      filetype                = 'BIN'
    importing
      filelength              = lv_file_size
    tables
      data_tab                = lt_data
    exceptions
      conversion_error        = 1
      file_open_error         = 2
      file_read_error         = 3
      invalid_type            = 4
      no_batch                = 5
      unknown_error           = 6
      invalid_table_width     = 7
      gui_refuse_filetransfer = 8
      customer_error          = 9
      no_authority            = 10
      bad_data_format         = 11
      header_not_allowed      = 12
      separator_not_allowed   = 13
      header_too_long         = 14
      unknown_dp_error        = 15
      access_denied           = 16
      dp_out_of_memory        = 17
      disk_full               = 18
      dp_timeout              = 19
      not_supported_by_gui    = 20
      error_no_gui            = 21
      others                  = 22.
  if sy-subrc <> 0.
    message e000(38) with 'Unable to upload the file'.
    gv_stop_copy = abap_true.
    exit.
  endif.


  open dataset lv_serv_name for output in binary mode.
  if sy-subrc <> 0.
    message e000(38) with 'Cannot open file on server'.
    gv_stop_copy = abap_true.
    exit.
  endif.

  describe table lt_data lines lv_lines.

  lv_len = 2550.

  loop at lt_data.
    "Special handling for the last line
    if sy-tabix = lv_lines.
      lv_len = lv_file_size - ( 2550 * ( lv_lines - 1 ) ).
    endif.

    transfer lt_data to lv_serv_name length lv_len.

  endloop.

  close dataset lv_serv_name.


  "If we're moving the file, then delete the original
  check pv_move_type = 'M'.

  call method cl_gui_frontend_services=>file_delete
    exporting
      filename             = lv_pc_name
    changing
      rc                   = lv_len
    exceptions
      file_delete_failed   = 1
      cntl_error           = 2
      error_no_gui         = 3
      file_not_found       = 4
      access_denied        = 5
      unknown_error        = 6
      not_supported_by_gui = 7
      wrong_parameter      = 8
      others               = 9.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.


endform.


*&---------------------------------------------------------------------*
*&      Form  FILE2PC
*&---------------------------------------------------------------------*
* Copy a file to the PC
*----------------------------------------------------------------------*
form file2pc  using    pv_server_node
                       pv_pc_node
                       pv_move_type
             changing pv_file_name.


  data: lv_pc_name   type string,
        lv_serv_name type string,
        lv_file_size type i,
        lv_len       type i,
        lv_lines     type i,
        lv_result    type c,
        lt_data      type rcgrepfile occurs 0 with header line.




  g_node_key = pv_server_node.
  clear lv_serv_name.
  do.
    read table gt_serv_tree into gs_tree with key node_key = g_node_key.
    if gs_tree-filetype = 'f'.
      pv_file_name = gs_tree-name.
    endif.

    perform build_path using gs_tree-name gv_servtype abap_true changing lv_serv_name.

    g_node_key = gs_tree-parent_node.
    if g_node_key is initial.
      exit.
    endif.
  enddo.

  g_node_key = pv_pc_node.
  clear lv_pc_name.
  do.
    read table gt_pc_tree into gs_tree with key node_key = g_node_key.
    perform build_path using gs_tree-name gv_pctype abap_false changing lv_pc_name.

    g_node_key = gs_tree-parent_node.
    if g_node_key is initial.
      exit.
    endif.
  enddo.

  concatenate lv_pc_name pv_file_name into lv_pc_name.

  clear: gv_stop_copy, gv_overwrite.

  if gv_answer is initial.
    "Check if the file exists on the PC
    call method cl_gui_frontend_services=>file_exist
      exporting
        file                 = lv_pc_name
      receiving
        result               = lv_result
      exceptions
        cntl_error           = 1
        error_no_gui         = 2
        wrong_parameter      = 3
        not_supported_by_gui = 4
        others               = 5.
    if sy-subrc <> 0.
* Implement suitable error handling here
    endif.

    if lv_result = abap_true.
      call function 'POPUP_TO_CONFIRM'
        exporting
          titlebar              = 'File already exists'
          text_question         = lv_serv_name
          text_button_1         = 'Overwrite'
          text_button_2         = 'Overwrite ALL'
          default_button        = '3'
          display_cancel_button = 'X'
        importing
          answer                = gv_answer
        exceptions
          text_not_found        = 1
          others                = 2.
      if sy-subrc <> 0.
* Implement suitable error handling here
      endif.

      if gv_answer = '3'.
        clear gv_answer.
        gv_stop_copy = abap_true.
        exit.
      endif.

      if gv_answer = '1'.
        clear gv_answer.
        gv_overwrite = abap_true.
      endif.

    endif.
  endif.

  if gv_answer is not initial.
    gv_overwrite = abap_true.
  endif.

  check gv_stop_copy is initial.

  "Copy the file
  data: mtext type string.
  open dataset lv_serv_name for input in binary mode message mtext.
  if sy-subrc <> 0.
    message e000(38) with 'Cannot open file on server'.
    wait up to 3 seconds.
    gv_stop_copy = abap_true.
    exit.
  endif.


  do.
    clear lv_len.
    clear lt_data.

    read dataset lv_serv_name into lt_data-orblk length lv_len.
    if sy-subrc <> 0.
      if lv_len > 0.
        lv_file_size = lv_file_size + lv_len.
        append lt_data.
      endif.
      exit.
    endif.

    lv_file_size = lv_file_size + lv_len.
    append lt_data.

  enddo.

  close dataset lv_serv_name.

  call function 'C13Z_DOWNLOAD'
    exporting
      bin_filesize            = lv_file_size
      filename                = lv_pc_name
      filetype                = 'BIN'
    importing
      filelength              = lv_len
    tables
      data_tab                = lt_data
    exceptions
      file_open_error         = 1
      file_write_error        = 2
      invalid_filesize        = 3
      invalid_type            = 4
      no_batch                = 5
      unknown_error           = 6
      invalid_table_width     = 7
      gui_refuse_filetransfer = 8
      customer_error          = 9
      no_authority            = 10
      header_not_allowed      = 11
      separator_not_allowed   = 12
      header_too_long         = 13
      dp_error_create         = 14
      dp_error_send           = 15
      dp_error_write          = 16
      unknown_dp_error        = 17
      access_denied           = 18
      dp_out_of_memory        = 19
      disk_full               = 20
      dp_timeout              = 21
      file_not_found          = 22
      dataprovider_exception  = 23
      control_flush_error     = 24
      not_supported_by_gui    = 25
      error_no_gui            = 26
      others                  = 27.
  if sy-subrc <> 0.
    message e000(38) with 'Unable to download the file'.
    gv_stop_copy = abap_true.
    exit.
  endif.


  "If this was a MOVE, then delete the original file
  check pv_move_type = 'M'.

  delete dataset lv_serv_name.


endform.


*&---------------------------------------------------------------------*
*&      Form  MATCH_MASK
*&---------------------------------------------------------------------*
* See if a given filename matches the selection screen mask
*----------------------------------------------------------------------*
form match_mask  using    pv_filename
                 changing pv_matched.

  data: lv_mask type string,
        lv_reg  type string,
        moff    type i,
        mlen    type i.

  pv_matched = abap_true.

  check p_mask is not initial.

  lv_mask = p_mask.
  clear lv_reg.
  while lv_mask is not initial.
    if lv_mask(1) = '*'.
      concatenate lv_reg '.{0,200}' into lv_reg. "Match anything from 0 to 200 chars
    else.
      if lv_mask(1) = '.'.
        "Escape the "." so that it matches exactly rather than generically
        concatenate lv_reg '\' lv_mask(1) into lv_reg.
      else.
        concatenate lv_reg lv_mask(1) into lv_reg. "Match this exact char
      endif.
    endif.
    shift lv_mask left.
  endwhile.

  find regex lv_reg in pv_filename match offset moff match length mlen.
  if sy-subrc <> 0.
    pv_matched = abap_false.
  else.
    "If we only matched a partial filename, then throw it away
    if mlen < strlen( pv_filename ).
      pv_matched = abap_false.
    endif.
  endif.


endform.

Saturday, November 18, 2017

Transferring data between SAP systems - improved version

Sometimes you find the need to transfer the data from a table in one client to another client or another system. E.g. when you've built a Z table and you've copied production down to the test environment or you might want to keep a copy of the table's contents before you make some change in case you mess things up and want to restore back to the old copy.

The program below will copy the data down to a text or binary file and will then read that file to reload the table again. Obviously there are a few caveats;
  • Table structures between the two systems must be completely identical.
  • Default parameters for things like date formats need to be identical between the two systems.
The program has been left with a deliberate compile bug in it at the point where you should put some kind of appropriate authorization check in place to prevent people from uploading junk into your system.

This is an improvement of a previous program I wrote as this one will handle GUIDs and text in foreign languages as well provided you use the binary format.


It's possible to limit the data that gets downloaded by using the Data selection button after you've selected the table and field names. This will dynamically build a new selection screen where you can select values to limit your data selection. You can also automatically split the file at a predefined record count if you're going to be working with really huge files.

When you're uploading you can decide if you want to skip existing records with the same key fields or simply overwrite them.

*&---------------------------------------------------------------------*
*& Report ZZDATA_TRANSFER
*&---------------------------------------------------------------------*
*& Use this program to transfer data between systems.
*& If you have data like unicode text that might get scrambled then
*& use binary mode to transfer the data.
*& Mark Langenhoven 2014 - 2017
*&---------------------------------------------------------------------*
report zzdata_transfer.


*--- Data declarations ------------------------------------------------
tables: dd03l.
type-pools:rsds.


data: begin of finalrec,
        fieldname like dd03l-fieldname,
        desc      like dd04t-ddtext,
      end of finalrec.
data: it_final  like finalrec occurs 0 with header line,
      lt_dd03l  like dd03l occurs 0 with header line,
      ls_dd03l  like dd03l,
      ls_dd04t  like dd04t,
      it_return like ddshretval occurs 0 with header line.

data: gv_where type rsds_twhere.


*--- Selection screen -------------------------------------------------
"Up or down direction
selection-screen begin of block dir with frame title dir.
selection-screen begin of line.
parameters p_down radiobutton group grp1 default 'X' user-command dib.
selection-screen comment 3(30) pdown.
selection-screen end of line.

selection-screen begin of line.
parameters p_up radiobutton group grp1.
selection-screen comment 3(30) pup.
selection-screen end of line.
selection-screen end of block dir.

"ASCII or Binary file type
selection-screen begin of block typ with frame title typ.
selection-screen begin of line.
parameters p_asc radiobutton group grp2 default 'X' user-command asc.
selection-screen comment 3(15) pasc.
selection-screen end of line.

selection-screen begin of line.
parameters p_bin radiobutton group grp2.
selection-screen comment 3(15) pbin.
selection-screen end of line.
selection-screen end of block typ.


"File name
selection-screen begin of block fil with frame title fil.
selection-screen begin of line.
selection-screen comment 1(15) pfile.
parameters p_file like rlgrap-filename.
selection-screen end of line.

"Add a header line to the output
selection-screen begin of line.
parameters p_head as checkbox default 'X'.
selection-screen comment 3(20) phead.
selection-screen end of line.

"Split file at NNN number of records
selection-screen begin of line.
selection-screen comment 1(25) pbrk.
parameters p_brk type i default '50000'.
selection-screen end of line.

selection-screen end of block fil.

"Table and field names
selection-screen begin of block tab with frame title tab.
selection-screen begin of line.
selection-screen comment 1(18) ptab.
parameters p_tab like dd03l-tabname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(15) pfield.
select-options: s_field for dd03l-fieldname no intervals.
selection-screen end of line.

selection-screen: pushbutton 1(18) p_btn user-command clk.

selection-screen end of block tab.

"Skip or overwrite uploaded data
selection-screen begin of block upd with frame title upd.
selection-screen begin of line.
parameters p_skip radiobutton group upg default 'X'.
selection-screen comment 3(28) pskip.
selection-screen end of line.

selection-screen begin of line.
parameters p_over radiobutton group upg.
selection-screen comment 3(28) pover.
selection-screen end of line.

selection-screen end of block upd.


initialization.
  pdown = 'Transfer data down to a file'.
  pup = 'Transfer data up from a file'.
  pasc = 'ASCII text file'.
  pbin = 'Binary file'.
  pfile = 'File name'.
  ptab = 'Table name'.
  pfield = 'Field selection'.
  p_btn = 'Data selection'.
  pskip = 'Skip existing records'.
  pover = 'Overwrite existing records'.
  pbrk = 'Break files into records'.
  phead = 'Header line'.

  dir = 'Direction'.
  typ = 'File type'.
  fil = 'File information'.
  tab = 'Table information'.
  upd = 'Update method'.



  "Grab any fieldnames the user wants to select by

at selection-screen on value-request for s_field-low.
  "Build a custom search help because the dropdown on dd03l is terrible
  refresh it_final.
  select tabname fieldname keyflag rollname from dd03l
    into corresponding fields of table lt_dd03l
  where tabname = p_tab
  order by position.

  "Ignore includes
  delete lt_dd03l where fieldname cs '.INCL'.

  loop at lt_dd03l.
    clear it_final.
    it_final-fieldname = lt_dd03l-fieldname.
    select single ddtext from dd04t into it_final-desc
    where rollname = lt_dd03l-rollname
    and   ddlanguage = sy-langu.
    append it_final.
  endloop.

  call function 'F4IF_INT_TABLE_VALUE_REQUEST'
    exporting
      retfield        = 'FIELDNAME'
      value_org       = 'S'
    tables
      value_tab       = it_final
      return_tab      = it_return
    exceptions
      parameter_error = 1
      no_values_found = 2
      others          = 3.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.

  loop at it_return.
    s_field-low = it_return-fieldval.
    s_field-sign = 'I'.
    s_field-option = 'EQ'.
    append s_field.
  endloop.

  sort s_field.
  delete adjacent duplicates from s_field.



at selection-screen on value-request for p_file.
  "Pop up a file selector for the user to choose a file
  data: objfile type ref to cl_gui_frontend_services.
  data: lv_rc    type i,
        ls_files type line of filetable,
        lt_files type filetable.

  check sy-batch is initial.

  create object objfile.
  call method cl_gui_frontend_services=>file_open_dialog
    exporting
      window_title            = 'Select file'
      default_extension       = 'TXT'
    changing
      file_table              = lt_files
      rc                      = lv_rc
    exceptions
      file_open_dialog_failed = 1
      cntl_error              = 2
      error_no_gui            = 3
      not_supported_by_gui    = 4
      others                  = 5.
  check sy-subrc = 0.

  read table lt_files into ls_files index 1.
  check sy-subrc = 0.

  p_file = ls_files-filename.


at selection-screen.
  if sy-ucomm = 'CLK'.
    if s_field[] is initial.
      message s000(38) with 'Select fields first'.
      exit.
    endif.
    perform restrict_data.
  endif.

  "Check if everything is filled prior to running
  if sy-ucomm = 'ONLI'.

    if p_file is initial.
      message e000(38) with 'Supply the filename'.
      exit.
    endif.

    if p_tab is initial.
      message e000(38) with 'Supply the table name'.
      exit.
    endif.

    select single * from dd03l into ls_dd03l
       where tabname = p_tab.
    if sy-subrc <> 0.
      message e000(38) with 'Invalid table name' p_tab.
      exit.
    endif.

  endif.


at selection-screen output.
  if p_up = abap_true.
    "Show the upload parameters
    loop at screen.
      if screen-name cs 'OVER' or
         screen-name cs 'SKIP'.
        screen-invisible = 0.
        modify screen.
      endif.
      if screen-name cs 'BTN' or
         screen-name cs 'FIELD' or
         screen-name cs 'BRK'.
        screen-invisible = 1.
        screen-input = 0.
        modify screen.
      endif.
    endloop.
  else.
    "Hide the upload parameters
    loop at screen.
      if screen-name cs 'OVER' or
         screen-name cs 'SKIP'.
        screen-invisible = 1.
        modify screen.
      endif.
      if screen-name cs 'BTN' or
         screen-name cs 'FIELD' or
         screen-name cs 'BRK'.
        screen-invisible = 0.
        modify screen.
      endif.
    endloop.
  endif.

  "No header record allowed on binary files
  if p_bin = abap_true.
    loop at screen.
      if screen-name cs 'HEAD'.
        screen-active = 0.
        modify screen.
      endif.
    endloop.
  endif.

  "Needed because SAP messes around with our stuff after the fact
  sort s_field.
  delete adjacent duplicates from s_field.



*=== Main program =====================================================
start-of-selection.
  if p_down = abap_true.
    perform download.
  else.
    if p_tab(1) <> 'Z'.
      message e000(38) with 'Only Z tables are allowed'.
      exit.
    endif.
    Build your authorization check here.
    perform upload.
  endif.


*&---------------------------------------------------------------------*
*&      Form  RESTRICT_DATA
*&---------------------------------------------------------------------*
* Use the user's selection to restrict which data will be downloaded
*----------------------------------------------------------------------*
form restrict_data.
  data: lv_title  like sy-title,
        lv_expr   type rsds_texpr,
        lt_tables like rsdstabs occurs 0 with header line,
        lt_fields like rsdsfields occurs 0 with header line,
        lv_selid  like rsdynsel-selid,
        lv_actnum like sy-tfill.

  refresh: lt_tables, lt_fields.
  clear: gv_where.

  lt_tables-prim_tab = p_tab.
  append lt_tables.

  loop at s_field.
    lt_fields-tablename = p_tab.
    lt_fields-fieldname = s_field-low.
    append lt_fields.
  endloop.

  call function 'FREE_SELECTIONS_INIT'
    exporting
      kind                     = 'T'
      expressions              = lv_expr
    importing
      selection_id             = lv_selid
      number_of_active_fields  = lv_actnum
    tables
      tables_tab               = lt_tables
      fields_tab               = lt_fields
    exceptions
      fields_incomplete        = 1
      fields_no_join           = 2
      field_not_found          = 3
      no_tables                = 4
      table_not_found          = 5
      expression_not_supported = 6
      incorrect_expression     = 7
      illegal_kind             = 8
      area_not_found           = 9
      inconsistent_area        = 10
      kind_f_no_fields_left    = 11
      kind_f_no_fields         = 12
      too_many_fields          = 13
      dup_field                = 14
      field_no_type            = 15
      field_ill_type           = 16
      dup_event_field          = 17
      node_not_in_ldb          = 18
      area_no_field            = 19
      others                   = 20.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.

  concatenate 'Restrict data selections for' p_tab into lv_title separated by space.

  call function 'FREE_SELECTIONS_DIALOG'
    exporting
      selection_id            = lv_selid
      title                   = lv_title
      tree_visible            = ' '
    importing
      where_clauses           = gv_where
      number_of_active_fields = lv_actnum
    tables
      fields_tab              = lt_fields
    exceptions
      internal_error          = 1
      no_action               = 2
      selid_not_found         = 3
      illegal_status          = 4
      others                  = 5.
  if sy-subrc <> 0.
    clear: gv_where.
  endif.

endform.


*&---------------------------------------------------------------------*
*&      Form  DOWNLOAD
*&---------------------------------------------------------------------*
* Download data to a file
*----------------------------------------------------------------------*
form download.

  data: lv_file  type string,
        lv_ftype type char10,
        lv_sep   type char01.

  data: ls_where    type rsds_where,
        lt_wheretab type rsds_where_tab,
        ls_wheretab type rsdswhere,
        lv_where    type string.

  data: begin of namerec,
          fieldname like dd03l-fieldname,
        end of namerec.

  data: lt_dyntab     type ref to data,
        lt_dyntab2    type ref to data,
        ls_dynwa      type ref to data,
        lt_cat        type table of lvc_s_fcat,
        lt_fields     like dd03l occurs 0 with header line,
        lt_fieldnames like namerec occurs 0 with header line,
        wa_fields     like dd03l,
        wa_cat        type lvc_s_fcat,
        lv_cnt        type i,
        lv_sel        type i,
        lv_tabix      type i,
        lv_filecnt(3) type n.

  field-symbols: <table> type table,
                 <load>  type table,
                 <wa>.


  select * from dd03l into table lt_fields
  where tabname = p_tab.

  sort lt_fields by position.
  delete lt_fields where fieldname cp '.INCLU*'.

  loop at lt_fields into wa_fields.
    lv_cnt = lv_cnt + 1.
    wa_cat-tabname = p_tab.
    wa_cat-fieldname = wa_fields-fieldname.
    wa_cat-col_pos = lv_cnt.
    wa_cat-inttype = wa_fields-inttype.
    wa_cat-datatype = wa_fields-datatype.
    wa_cat-intlen = wa_fields-intlen.
    wa_cat-seltext = wa_fields-fieldname.
    wa_cat-decimals = wa_fields-decimals.
    wa_cat-ref_field = wa_fields-fieldname.
    wa_cat-ref_table = p_tab.
    append wa_cat to lt_cat.
    clear wa_cat.
  endloop.
  call method cl_alv_table_create=>create_dynamic_table
    exporting
      it_fieldcatalog           = lt_cat
    importing
      ep_table                  = lt_dyntab
    exceptions
      generate_subpool_dir_full = 1
      others                    = 2.
  if sy-subrc <> 0.
    message e000(38) with 'Error creating dynamic table'.
    exit.
  endif.

  assign lt_dyntab->* to <table>.

  call method cl_alv_table_create=>create_dynamic_table
    exporting
      it_fieldcatalog           = lt_cat
    importing
      ep_table                  = lt_dyntab2
    exceptions
      generate_subpool_dir_full = 1
      others                    = 2.
  if sy-subrc <> 0.
    message e000(38) with 'Error creating dynamic table'.
    exit.
  endif.
  assign lt_dyntab2->* to <load>.

  "Create a work area for us to loop through
  create data ls_dynwa like line of <table>.
  assign ls_dynwa->* to <wa>.

  "Select the actual data to download
  if gv_where is not initial.
    read table gv_where into ls_where index 1.
    lt_wheretab = ls_where-where_tab.
    if lt_wheretab[] is not initial.
      clear lv_where.
      loop at lt_wheretab into ls_wheretab.
        concatenate lv_where ls_wheretab-line into lv_where separated by space.
      endloop.
      select * from (p_tab) into table <table>
      where (lv_where).
    endif.

  else.
    select * from (p_tab) into table <table>.
  endif.

  describe table <table>.
  if sy-tfill > 0.
    write: / 'Selected ', sy-tfill, 'records'.
  else.
    write: / 'No data selected'.
    exit.
  endif.

  lv_sel = sy-tfill.
  lv_filecnt = 1.


  loop at <table> into <wa>.
    lv_tabix = sy-tabix.
    append <wa> to <load>.
    check lv_tabix mod p_brk = 0 or lv_tabix = lv_sel.


    if lv_sel > p_brk and p_brk > 0.
      perform build_filename using lv_filecnt changing lv_file.
      lv_filecnt = lv_filecnt + 1.
    else.
      lv_file = p_file.
    endif.

    if p_asc = abap_true.
      lv_ftype = 'ASC'.
      lv_sep = 'X'.
    else.
      lv_ftype = 'BIN'.
      clear: lv_sep.
    endif.

    refresh lt_fieldnames.
    if p_head = abap_true and p_asc = abap_true.
      loop at lt_fields.
        lt_fieldnames = lt_fields-fieldname.
        append lt_fieldnames.
      endloop.
    endif.

    call function 'GUI_DOWNLOAD'
      exporting
        filename                = lv_file
        filetype                = lv_ftype
        write_field_separator   = lv_sep
      tables
        data_tab                = <load>
        fieldnames              = lt_fieldnames
      exceptions
        file_write_error        = 1
        no_batch                = 2
        gui_refuse_filetransfer = 3
        invalid_type            = 4
        no_authority            = 5
        unknown_error           = 6
        header_not_allowed      = 7
        separator_not_allowed   = 8
        filesize_not_allowed    = 9
        header_too_long         = 10
        dp_error_create         = 11
        dp_error_send           = 12
        dp_error_write          = 13
        unknown_dp_error        = 14
        access_denied           = 15
        dp_out_of_memory        = 16
        disk_full               = 17
        dp_timeout              = 18
        file_not_found          = 19
        dataprovider_exception  = 20
        control_flush_error     = 21
        others                  = 22.
    if sy-subrc <> 0.
      write: / 'Error creating file', sy-subrc.
    else.
      write: / 'Downloaded file:', lv_file.
    endif.

    refresh <load>.

  endloop.

endform.


*&---------------------------------------------------------------------*
*&      Form  UPLOAD
*&---------------------------------------------------------------------*
* Upload the data from a file
*----------------------------------------------------------------------*
form upload.

  data: lv_file  type string,
        lv_ftype type char10,
        lv_sep   type char01,
        lv_rc    type i.

  data: lt_dyntab type ref to data,
        ls_dynwa  type ref to data,
        ls_dynwa2 type ref to data,
        lt_cat    type table of lvc_s_fcat,
        lt_fields like dd03l occurs 0 with header line,
        wa_fields like dd03l,
        wa_cat    type lvc_s_fcat,
        lv_cnt    type i,
        lv_mandt,
        lv_where  type string,
        lv_tmp    type string.

  field-symbols: <table> type table,
                 <wa>,
                 <field>,
                 <skip>.


  lv_file = p_file.

  if p_asc = abap_true.
    lv_ftype = 'ASC'.
    lv_sep = 'X'.
  else.
    lv_ftype = 'BIN'.
    clear lv_sep.
  endif.


  select * from dd03l into table lt_fields
  where tabname = p_tab.

  sort lt_fields by position.
  delete lt_fields where fieldname cp '.INCLU*'.

  loop at lt_fields into wa_fields.
    lv_cnt = lv_cnt + 1.
    wa_cat-tabname = p_tab.
    wa_cat-fieldname = wa_fields-fieldname.
    wa_cat-col_pos = lv_cnt.
    wa_cat-inttype = wa_fields-inttype.
    wa_cat-datatype = wa_fields-datatype.
    wa_cat-intlen = wa_fields-intlen.
    wa_cat-seltext = wa_fields-fieldname.
    wa_cat-decimals = wa_fields-decimals.
    wa_cat-ref_field = wa_fields-fieldname.
    wa_cat-ref_table = p_tab.
    append wa_cat to lt_cat.
    clear wa_cat.
  endloop.
  call method cl_alv_table_create=>create_dynamic_table
    exporting
      it_fieldcatalog           = lt_cat
    importing
      ep_table                  = lt_dyntab
    exceptions
      generate_subpool_dir_full = 1
      others                    = 2.
  if sy-subrc <> 0.
    message e000(38) with 'Error creating dynamic table'.
    exit.
  endif.

  assign lt_dyntab->* to <table>.

  "Create a work area for us to loop through
  create data ls_dynwa like line of <table>.
  assign ls_dynwa->* to <wa>.
  create data ls_dynwa2 like line of <table>.
  assign ls_dynwa2->* to <skip>.

  if p_asc = abap_true and p_head = abap_true.
    perform remove_header changing lv_file.
  endif.

  call function 'GUI_UPLOAD'
    exporting
      filename                = lv_file
      filetype                = lv_ftype
      has_field_separator     = lv_sep
    tables
      data_tab                = <table>
    exceptions
      file_open_error         = 1
      file_read_error         = 2
      no_batch                = 3
      gui_refuse_filetransfer = 4
      invalid_type            = 5
      no_authority            = 6
      unknown_error           = 7
      bad_data_format         = 8
      header_not_allowed      = 9
      separator_not_allowed   = 10
      header_too_long         = 11
      unknown_dp_error        = 12
      access_denied           = 13
      dp_out_of_memory        = 14
      disk_full               = 15
      dp_timeout              = 16
      others                  = 17.
  if sy-subrc <> 0.
    write: / 'Upload file error', sy-subrc.
    exit.
  endif.

  "Delete the temporary file
  if p_asc = abap_true and p_head = abap_true.

    call method cl_gui_frontend_services=>file_delete
      exporting
        filename             = lv_file
      changing
        rc                   = lv_rc
      exceptions
        file_delete_failed   = 1
        cntl_error           = 2
        error_no_gui         = 3
        file_not_found       = 4
        access_denied        = 5
        unknown_error        = 6
        not_supported_by_gui = 7
        wrong_parameter      = 8
        others               = 9.
    if sy-subrc <> 0.
*     Implement suitable error handling here
    endif.

  endif.

  read table lt_fields with key fieldname = 'MANDT'.
  if sy-subrc = 0.
    lv_mandt = abap_true.
  else.
    lv_mandt = abap_false.
  endif.

  clear lv_cnt.

  loop at <table> into <wa>.
    "Map to the current client
    if lv_mandt = abap_true.
      assign component 'MANDT' of structure <wa> to <field>.
      <field> = sy-mandt.
    endif.

    "See if we want to skip existing records
    if p_skip = abap_true.
      "Build up a dynamic where clause to select with
      clear lv_where.
      loop at lt_fields where keyflag = abap_true.
        check lt_fields-fieldname <> 'MANDT'.
        assign component lt_fields-fieldname of structure <wa> to <field>.

        concatenate '''' <field> '''' into lv_tmp.
        concatenate lv_where 'AND' lt_fields-fieldname '=' lv_tmp into lv_where separated by space.

      endloop.

      "Remove the unneeded AND
      shift lv_where left by 4 places.

      select single * from (p_tab) into <skip>
      where (lv_where).
      if sy-subrc = 0.
        continue.
      endif.
    endif.

    modify (p_tab) from <wa>.
    lv_cnt = lv_cnt + 1.
  endloop.

  commit work.

  write: / 'Updated', lv_cnt , 'records'.

endform.


*&---------------------------------------------------------------------*
*&      Form  BUILD_FILENAME
*&---------------------------------------------------------------------*
* Build up a filename for the file split
*----------------------------------------------------------------------*
form build_filename  using    pv_cnt
                     changing pv_file.

  data: lv_1 type string,
        lv_2 type string.

  pv_file = p_file.
  split pv_file at '.' into lv_1 lv_2.

  concatenate lv_1 pv_cnt '.' lv_2 into pv_file.

endform.


*&---------------------------------------------------------------------*
*&      Form  REMOVE_HEADER
*&---------------------------------------------------------------------*
* Remove the header record from the file
*----------------------------------------------------------------------*
form remove_header  changing pv_file.

  data: lt_dummy type table of string,
        lt_path  type string occurs 0 with header line.

  call method cl_gui_frontend_services=>gui_upload
    exporting
      filename                = pv_file
    changing
      data_tab                = lt_dummy
    exceptions
      file_open_error         = 1
      file_read_error         = 2
      no_batch                = 3
      gui_refuse_filetransfer = 4
      invalid_type            = 5
      no_authority            = 6
      unknown_error           = 7
      bad_data_format         = 8
      header_not_allowed      = 9
      separator_not_allowed   = 10
      header_too_long         = 11
      unknown_dp_error        = 12
      access_denied           = 13
      dp_out_of_memory        = 14
      disk_full               = 15
      dp_timeout              = 16
      not_supported_by_gui    = 17
      error_no_gui            = 18
      others                  = 19.
  if sy-subrc <> 0.
* Implement suitable error handling here
  endif.

  check lt_dummy is not initial.

  delete lt_dummy index 1.

  split pv_file at '\' into table lt_path.
  describe table lt_path.
  delete lt_path index sy-tfill.

  clear pv_file.
  loop at lt_path.
    concatenate pv_file '\' lt_path into pv_file.
  endloop.
  shift pv_file left.
  concatenate pv_file '\tempheader.txt' into pv_file.

  call method cl_gui_frontend_services=>gui_download
    exporting
      filename                = pv_file
    changing
      data_tab                = lt_dummy
    exceptions
      file_write_error        = 1
      no_batch                = 2
      gui_refuse_filetransfer = 3
      invalid_type            = 4
      no_authority            = 5
      unknown_error           = 6
      header_not_allowed      = 7
      separator_not_allowed   = 8
      filesize_not_allowed    = 9
      header_too_long         = 10
      dp_error_create         = 11
      dp_error_send           = 12
      dp_error_write          = 13
      unknown_dp_error        = 14
      access_denied           = 15
      dp_out_of_memory        = 16
      disk_full               = 17
      dp_timeout              = 18
      file_not_found          = 19
      dataprovider_exception  = 20
      control_flush_error     = 21
      not_supported_by_gui    = 22
      error_no_gui            = 23
      others                  = 24.
  if sy-subrc <> 0.
*   Implement suitable error handling here
  endif.

endform.

Sunday, June 4, 2017

Adding a debit memo line to a repair order

Repair orders appear to look like normal sales orders in SAP and can be viewed and changed via VA03/VA02 as usual. However, when you want to change a line, then you need to click on the repair line and hit the repair button at the bottom of the screen.

If you want to change this line programatically, then you need to jump through a few more hoops as you cannot use the usual BAPIs to add or edit one of these lines. Below is the code to add a debit memo to the repair line;

  "Open the sales order for manipulation
  call function 'SD_SALES_DOCUMENT_READ'
    exporting
      document_number            = ls_vbak-vbeln
      status_buffer_refresh      = 'X'
      requisition_buffer_refresh = 'X'.


  "Update our line item
  refresh lt_itemkom.
  clear lt_itemkom.
  lt_itemkom-posnr = '900003'.
  lt_itemkom-updkz = 'I'.
  lt_itemkom-vkgru = '109'. "Debit memo
  lt_itemkom-menge = ls_vbap-kwmeng.
  lt_itemkom-matnr_g = ls_vbap-matnr.
  lt_itemkom-arktx_g = ls_vbap-arktx.
  append lt_itemkom.

  perform repairitems_generate(sapfv45p) tables lt_itemkom
                                                lt_serikom
                                         using  ls_vbap-uepos.

  "Save the order again
  call function 'SD_SALES_DOCUMENT_SAVE'
    exporting
      synchron                   = 'X'
      status_buffer_refresh      = 'X'
      requisition_buffer_refresh = 'X'.



  commit work and wait.

Wednesday, September 28, 2016

Creating a sales order with a One time customer

When using the BAPI_SALESORDER_CREATEFROMDAT2 bapi and you want to use a one time customer you need to link the ORDER_PARTNERS table with the PARTNERADDRESSES table.

This is done as follows;
ORDER_PARTNERS-ADDR_LINK = '1'.
PARTNERADDRESSES-ADDR_NO = '1'.

This will link the two tables and allow you to pass address and email information into the sales order for the one time customer.

Thursday, May 12, 2016

Creating a customer in HANA 1511

Creating a customer in HANA 1511 isn't as easy as it used to be. There's a new function, CVI_EI_INBOUND_MAIN, that is used to create all Business Partners. This has to be fed a lot of information before it will create a new customer. The code below will create a bare-bones customer with a single address.

*&---------------------------------------------------------------------*
*& Report ZZCUSTCREATE
*&---------------------------------------------------------------------*
*& Test program to create a customer
*&---------------------------------------------------------------------*
report zzcustcreate.


data: lt_data   type cvis_ei_extern_t,
      lt_return type bapiretm,
      ls_return type bapireti,
      ls_retmsg type line of bapiretct,
      lv_text   type string.

data: wa_data     like line of lt_data,
      wa_role     type bus_ei_bupa_roles,
      wa_relation type burs_ei_extern,
      wa_paadr    type bus_ei_bupa_address,
      wa_company  type cmds_ei_company.

data: lv_guid    type guid_32,
      lv_pguid   like but000-partner_guid,
      lv_partner like wa_data-partner-header-object_instance-bpartner.


start-of-selection.

  lv_partner = '0017100152'.

  select single partner_guid from but000 into lv_pguid
      where partner = lv_partner.
  if sy-subrc = 0.
    lv_guid = lv_pguid.
  else.
    call method cl_system_uuid=>if_system_uuid_static~create_uuid_c32
      receiving
        uuid = lv_guid.
  endif.


*  Create customer
  wa_data-partner-header-object_task = 'M'.
  wa_data-partner-header-object_instance-bpartner = lv_partner. "Because BP03 is externally numbered
  wa_data-partner-header-object_instance-bpartnerguid = lv_guid.



*--- Partner / Central data / common --------------------------------
  wa_data-partner-central_data-common-data-bp_control-category = '2'. "Organization
  wa_data-partner-central_data-common-data-bp_control-grouping = 'BP03'. "Grouping

  wa_data-partner-central_data-common-data-bp_centraldata-searchterm1 = 'MARKLANGENHOVEN'.

  wa_data-partner-central_data-common-data-bp_organization-name1 = 'Marks LLC'.

  wa_data-partner-central_data-common-data-bp_group-namegroup1 = 'MARKLLC'.

  wa_data-partner-central_data-common-datax-bp_centraldata-searchterm1 = abap_true.
  wa_data-partner-central_data-common-datax-bp_organization-name1 = abap_true.
  wa_data-partner-central_data-common-datax-bp_group-namegroup1 = abap_true.


*--- Partner / Central data / Address -------------------------------
  wa_paadr-task = 'M'.
  wa_paadr-data_key-operation = 'XXDFLT'.
  wa_paadr-data-postal-data-city = 'Beverly Hills'.
  wa_paadr-data-postal-data-postl_cod1 = '90210'.
  wa_paadr-data-postal-data-street = '1234 Main St'.
  wa_paadr-data-postal-data-country = 'US'.
  wa_paadr-data-postal-data-region = 'CA'.
  wa_paadr-data-postal-data-langu = 'E'.

  wa_paadr-data-postal-datax-city = abap_true.
  wa_paadr-data-postal-datax-postl_cod1 = abap_true.
  wa_paadr-data-postal-datax-street = abap_true.
  wa_paadr-data-postal-datax-country = abap_true.
  wa_paadr-data-postal-datax-region = abap_true.
  wa_paadr-data-postal-datax-langu = abap_true.

  wa_paadr-currently_valid = abap_true.
  append wa_paadr to wa_data-partner-central_data-address-addresses.


*--- Partner / Central data / role ----------------------------------
  wa_role-task = 'M'. "Modify
  wa_role-data_key = 'FLCU01'. "Role key - customer
  wa_role-data-rolecategory = 'FLCU01'.
  wa_role-data-valid_from = sy-datum.
  wa_role-data-valid_to = '99991231'.
  wa_role-currently_valid = abap_true.

  wa_role-datax-valid_from = abap_true.
  wa_role-datax-valid_to = abap_true.

  append wa_role to wa_data-partner-central_data-role-roles.
  wa_data-partner-central_data-role-current_state = abap_true.


*--- Partner relation / header ---------------------------------
  wa_relation-header-object_instance-partner1-identificationcategory = 'FLCU01'.
  append wa_relation to wa_data-partner_relation.
  wa_relation-header-object_task = 'I'.


*--- Customer / Company data ------------------------------------
  wa_company-task        = 'M'.    "Modify
  wa_company-data_key    = '1710'. " company code
  wa_company-data-zterm  = '0002'. " terms of payment

  wa_company-datax-zterm = 'X'.

  append wa_company to wa_data-customer-company_data-company.


*--- Customer / Header --------------------------------------------
  wa_data-customer-header-object_task = 'I'.
  wa_data-customer-header-object_instance = lv_partner.



*--- Customer / Central data -------------------------------------
  wa_data-customer-central_data-address-task = 'M'. "Modify
  wa_data-customer-central_data-address-postal-data-from_date = sy-datum.
  wa_data-customer-central_data-address-postal-data-to_date = '99991231'.
  wa_data-customer-central_data-address-postal-data-name = 'Mark Langenhoven'.

  wa_data-ensure_create-create_customer = abap_true.

  "Finally fill the main data structure
  append wa_data to lt_data.


  call function 'CVI_EI_INBOUND_MAIN'
    exporting
      i_data   = lt_data
    importing
      e_return = lt_return.

  call function 'BAPI_TRANSACTION_COMMIT'.

  loop at lt_return into ls_return.
    loop at ls_return-object_msg into ls_retmsg.
      message id ls_retmsg-id type 'S' number ls_retmsg-number into lv_text
                  with ls_retmsg-message_v1 ls_retmsg-message_v2 ls_retmsg-message_v3 ls_retmsg-message_v4.
      write: / ' ', ls_retmsg-type, ls_retmsg-id, ls_retmsg-number, / '>>', lv_text.
    endloop.
  endloop.

  write: / 'Done'.

Thursday, January 21, 2016

Finding the correct BADi for the job

To be able to easily find the exact right BADi you need you can follow the steps below;

  • Go to t-code SE24
  • Pull up class CL_EXITHANDLER
  • Double click the GET_INSTANCE method
  • Put a break point on the CASE's sy-subrc line. (Roundabout line 28)
  • Now run the t-code you want the BADi for and check the EXIT_NAME field for the name of the BADI


Monday, November 16, 2015

Finding related data in SAP tables

Sometimes you need to find a seemingly obscure connection for some data that you have. E.g. you have a delivery number and you would like to know all the tables that that exact delivery number appears in so that you can search those records to find the second piece of information you're after.

Maybe you're trying to find all the links between a batch and a delivery so one of the tables you'll see is CHVW which might be exactly what you're after in your program's selections.

This is where my ZZFINDER program comes in handy. I use it multiple times on each project that I am on. You fill out the selection screen with the data you're after (including any leading zeroes) and hit F8.


The program will then come back with a list of table and field names to show you where this piece of data was found in the system.

So, here's the code to do this;

report zzfinder
       no standard page heading line-size 132.
* Mark Langenhoven 2015/11/14

*--- Data declarations ----------------------------------------------
"Record searching
tables: dd03l, dd02l.

"Table searching
data: begin of datarec,
        tabname   like dd03l-tabname,
        tabtext   like dd02t-ddtext,
        fieldname like dd03l-fieldname,
        fieldtext like dd03t-ddtext,
        data(80),
      end of datarec.
data: begin of fieldrec,
        tabname   like dd03l-tabname,
        fieldname like dd03l-fieldname,
        tabclass  like dd02l-tabclass,
      end of fieldrec.

data: gt_tfields like fieldrec occurs 0 with header line.
data: gt_tdata   like datarec occurs 0 with header line.


*--- Selection screen -----------------------------------------------
selection-screen begin of block a1 with frame.
selection-screen begin of line.
selection-screen comment 1(22) pdata.
parameters: p_data type adrnr_txt.
selection-screen end of line.
selection-screen end of block a1.

selection-screen begin of block a2 with frame.

"Manual field definition
selection-screen begin of block a2a with frame.
selection-screen begin of line.
selection-screen comment 1(22) stype.
select-options s_type for dd03l-datatype.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22) sleng.
select-options s_leng for dd03l-leng.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22) sdec.
select-options s_dec for dd03l-decimals.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22) sdom.
select-options s_dom for dd03l-domname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22) skey.
select-options s_key for dd03l-keyflag no intervals.
selection-screen end of line.

selection-screen end of block a2a.

selection-screen comment 1(38) eor.

"Field definition by example
selection-screen begin of block a2b with frame.
selection-screen begin of line.
selection-screen comment 1(22) ptabnam.
parameters p_tabnam like dd03l-tabname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22) pfieldn.
parameters p_fieldn like dd03l-fieldname.
selection-screen end of line.

selection-screen end of block a2b.

selection-screen end of block a2.

"Matching strategy
selection-screen begin of block a3 with frame.
selection-screen begin of line.
selection-screen comment 1(15) pexact.
parameters p_exact radiobutton group smde.


selection-screen comment 25(15) paddbf.
parameters p_addbf radiobutton group smde.
selection-screen end of line.

selection-screen end of block a3.

"Search limits
selection-screen begin of block a4 with frame.
selection-screen comment 1(35) slimit.
selection-screen begin of line.
selection-screen comment 1(22) stable.
select-options s_table for dd03l-tabname.
selection-screen end of line.

selection-screen begin of line.
selection-screen comment 1(22) sfield.
select-options s_field for dd03l-fieldname.
selection-screen end of line.

"Exclude tables starting with a slash
selection-screen begin of line.
parameters: p_noslsh as checkbox default 'X'.
selection-screen comment 5(22) snoslash.
selection-screen end of line.

selection-screen end of block a4.



initialization.
  pdata   = 'Data to find'.
  stype   = 'Data type'.
  sleng   = 'Data length'.
  sdec    = 'Num. of decimals'.
  sdom    = 'Domain name'.
  skey    = 'Key flag'.
  eor     = 'Fill in block above OR block below'.
  ptabnam = 'Reference table'.
  pfieldn = 'Reference field'.
  pexact  = 'Match exactly'.
  paddbf  = 'Match subtext'.
  slimit  = 'Search limits:'.
  stable  = 'Search tables'.
  sfield  = 'Search fields'.
  snoslash = 'Exclude tables with /'.


at selection-screen.
  perform validate_inputs.

*=== Main program ===================================================
start-of-selection.
  "Search through all tables to find some data
  perform search_all_tables.


at line-selection.
  perform goto_table using sy-cucol sy-lisel.


*&---------------------------------------------------------------------*
*&      Form  search_all_tables
*&---------------------------------------------------------------------*
form search_all_tables.

  "Check for wild cards
  if p_data cs '*'.
    p_addbf = abap_true.
    p_exact = abap_false.
    "Strip off the * because the selects don't like them
    translate p_data using ' `'.
    translate p_data using '* '.
    condense p_data no-gaps.
    translate p_data using '` '.
    message s000(38) with 'Subset matching selected for wildcards'.
  endif.

  perform find_fields tables gt_tfields.

  perform find_data tables gt_tfields
                             gt_tdata.

  perform disp_data tables gt_tdata.

endform.                    "search_all_tables



*&---------------------------------------------------------------------*
*&      Form  VALIDATE_INPUTS
*&---------------------------------------------------------------------*
* Make sure we have valid stuff entered
*----------------------------------------------------------------------*
form validate_inputs .
  if p_data is initial.
    message e000(38) with 'Enter some data to search for'.
  endif.

  "See if the user hasn't defined the field in some way or another
  if s_type[] is initial and
     s_dom[] is initial and
     p_tabnam is initial and
     p_fieldn is initial.
    message e000(38) with 'Enter field definitions'.
  endif.

  if p_tabnam is not initial and
     p_fieldn is initial.
    message e000(38) with 'Enter a table and field name in the definition'.
  endif.
  if p_tabnam is initial and
     p_fieldn is not initial.
    message e000(38) with 'Enter a table and field name in the definition'.
  endif.

endform.                    " VALIDATE_INPUTS


*&---------------------------------------------------------------------*
*&      Form  find_fields
*&---------------------------------------------------------------------*
* Find the fields which match our search criteria
*----------------------------------------------------------------------*
form find_fields  tables   pt_fields structure fieldrec.

  data: begin of dd02lrec,
          tabname  like dd02l-tabname,
          tabclass like dd02l-tabclass,
        end of dd02lrec.

  data: lt_dd02l   like dd02lrec occurs 0 with header line,
        lt_dd02l2  like dd02lrec occurs 0 with header line,
        lv_lines   type i,
        lv_msg(50) type c,
        lt_fields  like fieldrec occurs 0 with header line.


  "Use the alternate field definition if the user has requested it
  perform build_fields.

  "If we are not dealing with an exact match, then allow for larger data elements
  if p_addbf = abap_true.
    loop at s_leng .
      if s_leng-option = 'EQ'.
        s_leng-option = 'GE'.
        modify s_leng.
      endif.
    endloop.
  endif.

  "Exclude tables starting with /
  if p_noslsh = abap_true.
    read table s_table with key low = '/*'.
    if sy-subrc <> 0.
      s_table-low = '/*'.
      s_table-option = 'CP'.
      s_table-sign = 'E'.
      append s_table.
    endif.

  endif.

  call function 'SAPGUI_PROGRESS_INDICATOR'
    exporting
      text = 'Getting fields...'.


  select tabname fieldname from dd03l
        into corresponding fields of table lt_fields
        package size 10 "Can run for a long time
        where tabname in s_table
        and   fieldname in s_field
        and   datatype in s_type
        and   leng in s_leng
        and   decimals  in s_dec
        and   domname in s_dom
        and   keyflag in s_key.

    append lines of lt_fields to pt_fields.
    describe table pt_fields.
    lv_msg = |Getting fields... { sy-tfill }|.

    call function 'SAPGUI_PROGRESS_INDICATOR'
      exporting
        text = lv_msg.


  endselect.


  check pt_fields[] is not initial.

  "Reduce the select time on the next two selects
  refresh lt_fields.
  append lines of pt_fields to lt_fields.
  sort lt_fields by tabname.
  delete adjacent duplicates from lt_fields comparing tabname.

  call function 'SAPGUI_PROGRESS_INDICATOR'
    exporting
      text = 'Checking tables...'.

  "Make sure we only grab tables and not structures
  select tabname tabclass from dd02l into table lt_dd02l
         for all entries in lt_fields
         where tabname = lt_fields-tabname
         and ( tabclass = 'INTTAB' or
               tabclass = 'APPEND' or
               tabclass = 'VIEW' ).

  "Only activated tables allowed
  select tabname tabclass from dd02l into table lt_dd02l2
         for all entries in lt_fields
         where tabname = lt_fields-tabname
         and   as4local <> 'A'.
  if sy-subrc = 0.
    append lines of lt_dd02l2 to lt_dd02l.
  endif.

  sort lt_dd02l by tabname.
  delete adjacent duplicates from lt_dd02l comparing tabname.


  loop at lt_dd02l.
    delete pt_fields where tabname = lt_dd02l-tabname.

    check sy-tabix mod 100 = 0.
    describe table pt_fields.
    lv_msg = |Reducing fields... { sy-tfill }|.

    call function 'SAPGUI_PROGRESS_INDICATOR'
      exporting
        text = lv_msg.

  endloop.


  select tabname tabclass from dd02l into table lt_dd02l
           for all entries in pt_fields
           where tabname = pt_fields-tabname.
  sort lt_dd02l by tabname.

  loop at pt_fields.
    read table lt_dd02l with key tabname = pt_fields-tabname
                                binary search.
    pt_fields-tabclass = lt_dd02l-tabclass.
    modify pt_fields.
  endloop.


  describe table pt_fields lines lv_lines.
  write:/ 'Number of matching fields found: ', lv_lines.

*  message 'Done' type 'S'.

  call function 'SAPGUI_PROGRESS_INDICATOR'
    exporting
      text = 'Fields selected'.

endform.                    " find_fields



*&---------------------------------------------------------------------*
*&      Form  find_data
*&---------------------------------------------------------------------*
* Search through our list of fields to see if we can find a match on
* our data
*----------------------------------------------------------------------*
form find_data  tables   pt_fields structure fieldrec
                         pt_data structure datarec.

  data: begin of tabrec,
          data(80),
        end of tabrec.
  data: lt_tab       like tabrec occurs 0 with header line,
        lv_lines     type i,
        lv_total     type i,
        lv_tables    type i,
        lv_count     type i,
        lv_perc      type i,
        lv_cond      type string,
        lv_tabix(10),
        lv_msg(80).

  data: ls_old        like datarec,
        lv_counter(3) type n.


  check pt_fields[] is not initial.

  describe table pt_fields lines lv_tables.

  loop at pt_fields .
    refresh lt_tab.

    "Update the job log with a status message
    lv_count = sy-tabix mod 100.
    if lv_count = 0.
*      WRITE sy-tabix TO lv_tabix.
      lv_msg = | Searching table { sy-tabix } of { lv_tables } |.
      if lv_tables = 0.
        lv_perc = 0.
      else.
        lv_perc = sy-tabix * 100 / lv_tables.
      endif.

      call function 'SAPGUI_PROGRESS_INDICATOR'
        exporting
          percentage = lv_perc
          text       = lv_msg.
    endif.

    refresh lt_tab.
    if p_exact = abap_true.
      concatenate '''' p_data '''' into lv_cond.
      concatenate pt_fields-fieldname '=' lv_cond into lv_cond separated by space.
      select single (pt_fields-fieldname) from (pt_fields-tabname)
          into tabrec
          where (lv_cond).
      append tabrec to lt_tab.

    else.
      if pt_fields-tabclass = 'POOL' or
         pt_fields-tabclass = 'CLUSTER'.
        "Cannot optimize with DISTINCT on pool or cluster tables
        select (pt_fields-fieldname) from (pt_fields-tabname)
            into table lt_tab.

      else.

        select distinct (pt_fields-fieldname) from (pt_fields-tabname)
            into table lt_tab.

      endif.
    endif.

    if sy-subrc = 0.

      describe table lt_tab lines lv_lines.
      lv_total = lv_total + lv_lines.

      if p_exact = abap_true.
        "Match the values exactly
        read table lt_tab with key data = p_data.

        if sy-subrc = 0.

          move-corresponding pt_fields to pt_data.
          pt_data-data = lt_tab-data.
          append pt_data.

        endif.
      else.
        "Match any string which contains our string
        loop at lt_tab .
          find p_data in lt_tab-data.
          if sy-subrc = 0.

            move-corresponding pt_fields to pt_data.
            pt_data-data = lt_tab-data.
            append pt_data.

          endif.

        endloop.
      endif.

    endif.
  endloop.


  "Clean up the output a little bit
  sort pt_data.
  delete adjacent duplicates from pt_data.

  loop at pt_data.
    if pt_data-tabtext is initial.
      select single ddtext from dd02t into pt_data-tabtext
             where tabname = pt_data-tabname
             and   ddlanguage = sy-langu.
      modify pt_data transporting tabtext where tabname = pt_data-tabname.
    endif.

    if pt_data-fieldtext is initial.
      select single ddtext from dd03t into pt_data-fieldtext
        where tabname = pt_data-tabname
        and   fieldname = pt_data-fieldname
        and   ddlanguage = sy-langu.
      if sy-subrc <> 0.
        select single ddtext from dd04t into pt_data-fieldtext
          where rollname = pt_data-fieldname
          and   ddlanguage = sy-langu.
      endif.

      modify pt_data transporting fieldtext where fieldname = pt_data-fieldname.
    endif.
  endloop.

  write: / 'Number of data items checked   : ', lv_total.
  write: /.

endform.                    " find_data


*&---------------------------------------------------------------------*
*&      Form  disp_data
*&---------------------------------------------------------------------*
* Display the data we found
*----------------------------------------------------------------------*
form disp_data  tables   pt_data structure datarec.

  data: lv_lines(5) type n.
  data: ls_old         like datarec,
        lv_count       type i,
        lv_line(90),
        lv_tabcount(5) type n.

  "First write down what we searched for - useful for running multiple
  "background jobs
  write: / 'Searched for: '.
  write: / p_data.

  skip.

  lv_count = 0.
  lv_tabcount = 0.
  loop at pt_data .
    "If we've searched for an exact value then there's no need to
    "display it for every table
    if p_exact is initial.

      if pt_data-tabname = ls_old-tabname and
         pt_data-fieldname = ls_old-fieldname.
        lv_count = lv_count + 1.
        if lv_count = 1.
          write: / '|        Multiple values found         ' color col_group,
                   at 86 '|'.
        endif.
      else.
        "If we have a single value then write it out for us to see
        if lv_count = 0 and ls_old is not initial.
          write: / '|', ls_old-data, at 86 '|'.
        endif.
        lv_count = 0.
      endif.

    endif.

    ls_old = pt_data.
    if lv_count > 0.
      continue.
    endif.

    uline (86).
    write: / '|', '(Data)' hotspot,
             pt_data-tabname color col_heading hotspot,
             pt_data-fieldname color col_heading hotspot,
             at 86 '|'.
    write: / '|', '      ',
             pt_data-tabtext(30) color col_normal,
             pt_data-fieldtext(30) color col_normal,
             at 86 '|'.

    lv_tabcount = lv_tabcount + 1.

  endloop.

  if lv_count = 0 and ls_old is not initial.
    write: / '|', '   ', ls_old-data, at 86 '|'.
  endif.
  uline (86).


  describe table pt_data lines lv_lines.

  skip.
  "Format the output a little bit
  concatenate '$Found$' lv_lines '$records$in$' lv_tabcount '$tables' into lv_line.
  translate lv_line using '0 '.
  condense lv_line no-gaps.
  translate lv_line using '$ '.
  write: / lv_line.

  write: / .

  write: / ' Done. '.

endform.                    " disp_data


*&---------------------------------------------------------------------*
*&      Form  build_fields
*&---------------------------------------------------------------------*
*If the user specified a table and field name, then use that to build up
*the datatype and other field parameters,
*----------------------------------------------------------------------*
form build_fields .

  data: ls_dd03l like dd03l.

  check p_tabnam is not initial and
        p_fieldn is not initial.

  select single * from dd03l into ls_dd03l
        where tabname = p_tabnam
        and   fieldname = p_fieldn.

  check sy-subrc = 0.

  refresh: s_type, s_leng, s_dec, s_dom, s_key.

  s_type-low = ls_dd03l-datatype.
  s_type-sign = 'I'.
  s_type-option = 'EQ'.
  append s_type.

  s_leng-low = ls_dd03l-leng.
  s_leng-sign = 'I'.
  s_leng-option = 'EQ'.
  append s_leng.

  s_dec-low = ls_dd03l-decimals.
  s_dec-sign = 'I'.
  s_dec-option = 'EQ'.
  append s_dec.

  s_dom-low = ls_dd03l-domname.
  s_dom-sign = 'I'.
  s_dom-option = 'EQ'.
  append s_dom.

  if ls_dd03l-keyflag = abap_true.
    s_key-low = ls_dd03l-keyflag.
    s_key-sign = 'I'.
    s_key-option = 'EQ'.
    append s_key.
  endif.

endform.                    " build_fields


*&---------------------------------------------------------------------*
*&      Form  goto_table
*&---------------------------------------------------------------------*
* Jump to the selected table
*----------------------------------------------------------------------*
form goto_table  using pv_pos
                       pv_line.

  data: tabname      like dd03l-tabname,
        fieldname    like dd03l-fieldname,
        ls_gref      like tbprogref,
        progname     like rsvar-report,
        lv_dummy(10),
        lv_line(10),
        lt_sscr      like rsscr occurs 0 with header line,
        ls_dd03l     like dd03l,
        ls_dd04l     like dd04l.

  data: lt_params type table of rsparams,
        ls_param  type rsparams.



  split pv_line at space into lv_line lv_dummy tabname fieldname.
  condense: tabname, fieldname.

  set parameter id 'DTB' field tabname.
  if pv_pos > 9.
    "The user wants to see the table and add more
    "selections to it
    call transaction 'SE16' and skip first screen.
    exit.
  endif.


  "User has selected the (Data) hotspot
  "See if we can plug the field name in via a parameter ID as well
  "so that we can go direct to the data instead of the data
  "selection screen
  select single * from dd03l into ls_dd03l
             where tabname = tabname
             and fieldname = fieldname.
  if sy-subrc = 0.
    select single * from dd04l into ls_dd04l
            where rollname = ls_dd03l-rollname
            and   domname = ls_dd03l-domname.
    if sy-subrc = 0 and ls_dd04l-memoryid is not initial.
      set parameter id ls_dd04l-memoryid field p_data.
    endif.
  endif.

  select single * from tbprogref into ls_gref
          where tabname = tabname.
  if sy-subrc <> 0.
    "If we can't seem to find a program, then just
    "call the screen and let it sort the nonsense out
    call transaction 'SE16' and skip first screen.
  else.
    "Try to call the program manually with our additional
    "selection parameters
    concatenate '/1BCDWB/DB'  tabname into progname.

    load report progname part 'SSCR' into lt_sscr.

    refresh lt_params.
    loop at lt_sscr.
      if lt_sscr-dbfield cs fieldname.
        "Add our field to this selection
        ls_param-selname = lt_sscr-name.
        ls_param-kind = lt_sscr-kind.
        ls_param-option = 'EQ'.
        ls_param-sign = 'I'.
        "Put in all the fields we found in our earlier search
        loop at gt_tdata where tabname = tabname
                        and fieldname = fieldname.
          ls_param-low = gt_tdata-data.
          append ls_param to lt_params.
        endloop.
      endif.
    endloop.

    "Display the data from the table directly the way
    "SE16 would
    call function 'RS_TABLE_LIST_CREATE'
      exporting
        table_name         = tabname
      tables
        seltab             = lt_params
      exceptions
        table_is_structure = 1
        table_not_exists   = 2
        db_not_exists      = 3
        no_permission      = 4
        no_change_allowed  = 5
        others             = 6.
    if sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.

  endif.


endform.                    " goto_table