Registration

Dear SAP Community Member,
In order to fully benefit from what the SAP Community has to offer, please register at:
http://scn.sap.com
Thank you,
The SAP Community team.
Skip to end of metadata
Go to start of metadata

Report ZRMM_MATERIAL_MASTER Line-size 132
               no standard page heading.
*$*$--------------------------------------------------------------------
*$*$ Object Name:        ZRMM_MATERIAL_MASTER
*$*$ Author:             Aveek Ghose
*$*$ Date:               20070314
*$*$ Copyright:
*$*$ Transport Number:
*$*$
*$*$ Logical Database:
*$*$ SAPScript name:
*$*$ Application Area:   MM
*$*$ Description:        Material Master Data
*$*$
*$*$ Development ID#:    RDD3
*$*$ Incident Number:    0000000000
*$*$
*$*$ Purpose:
*$*$--------------------------------------------------------------------
*$*$ Correction #
*$*$ Modified By
*$*$ Date
*$*$ Transport Number
*$*$--------------------------------------------------------------------

*$*$--------------------------------------------------------------------
*$*$ Include programs
*$*$--------------------------------------------------------------------

 include zcommon_forms.

*$*$--------------------------------------------------------------------
*$*$   Data Declarations
*$*$--------------------------------------------------------------------

*$*$   Constants

* Constants for ALV Events declaration
CONSTANTS: BEGIN OF C_alv_events,
              top_of_page(12) TYPE c VALUE 'TOP_OF_PAGE',  "Top Of Page
              end_of_page(12) TYPE c VALUE 'END_OF_PAGE',  "End Of Page
           End of C_alv_events.

* Constants for yes Flag
CONSTANTS C_check(1)   TYPE c    VALUE 'X'.                "Flag

*$*$   Types
* Structure for storing final output data
types: begin of TY_outdata,
        WERKS       TYPE   MARC-WERKS,          "Plant
        MATKL       TYPE   MARA-MATKL,          "Material group
        PRCTR       TYPE   MARC-PRCTR,          "Profit Center
        MTART       TYPE   MARA-MTART,          "Material type
        MATNR       TYPE   MARA-MATNR,          "Material number
        MAKTX       TYPE   MAKT-MAKTX,          "Mat Description
        DISLS       TYPE   MARC-DISLS,          "Lot size
        BESKZ       TYPE   MARC-BESKZ,          "Procurement Typ
        FXHOR       TYPE   MARC-FXHOR,          "Planning time
end of TY_outdata.

* Structure for select from table MARC MARA MAKT
types: begin of TY_MARC_MARA_MAKT,
        WERKS       TYPE   MARC-WERKS,          "Plant
        MATNR       TYPE   MARC-MATNR,          "testMaterial
        PRCTR       TYPE   MARC-PRCTR,          "Profit Center
        DISLS       TYPE   MARC-DISLS,          "Lot size
        BESKZ       TYPE   MARC-BESKZ,          "Procurement
        FXHOR       TYPE   MARC-FXHOR,          "Plng time fence
        MTART       TYPE   MARA-MTART,          "Material Type
        MATKL       TYPE   MARA-MATKL,          "Material Group
        MAKTX       TYPE   MAKT-MAKTX,          "Description
end of TY_MARC_MARA_MAKT.

* Structure for select from table KNA1
types: begin of TY_KNA1,
        KUNNR       TYPE   KNA1-KUNNR,          "Customer
end of TY_KNA1.

*$*$   Internal Tables

* Internal table for output data
data I_outdata type standard table of TY_outdata initial size 0.

* Internal table for data from table MARC_MARA_MAKT
data I_MARC_MARA_MAKT type standard table
               of TY_MARC_MARA_MAKT initial size 0.

* Internal table for data from table KNA1
data I_KNA1 type standard table of TY_KNA1 initial size 0.

* Internal table for ALV Field Catalog
data I_fieldcat type slis_t_fieldcat_alv.

* Internal table for ALV field Sort Catalog
data I_sortcat type slis_t_sortinfo_alv.

* Internal table for ALV Field Events
data I_event type slis_t_event.

* Internal table for ALV Header declarations
data I_alv_header type slis_t_listheader.

* Error Internal table
data I_errors type standard table of bapiret2 initial size 0.

*$*$   Workareas

* Work area for output data
data WA_outdata type TY_outdata.

* Work area for structure TY_MARC_MARA_MAKT
data WA_MARC_MARA_MAKT type TY_MARC_MARA_MAKT.

* Work area for structure TY_KNA1
data WA_KNA1 type TY_KNA1.

* Work area for ALV Field layout
data WA_layout type slis_layout_alv.

* Work area for Variant data for ALV
data WA_variant type disvariant.

* Error Work area
data WA_errors type bapiret2.

*$*$   Variables

* Variable declaration for Select-Option: S_WERKS
Data G_WERKS type MARC-WERKS.

* Variable declaration for Select-Option: S_MTART
Data G_MTART type MARA-MTART.

* Variable declaration for Select-Option: S_MATKL
Data G_MATKL type MARA-MATKL.

* Variable declaration for Select-Option: S_MATNR
Data G_MATNR type MARA-MATNR.

*$*$   Flags

*$*$--------------------------------------------------------------------
*$*$ Selection criteria
*$*$--------------------------------------------------------------------
Selection-Screen Begin Of Block A With Frame Title text-001.

* Select Options: S_WERKS
Selection-Screen Begin Of Line.
Selection-Screen Comment 2(22) text-002.
Select-Options S_WERKS for G_WERKS Obligatory.
Selection-Screen End Of Line.

* Select Options: S_MTART
Selection-Screen Begin Of Line.
Selection-Screen Comment 2(22) text-004.
Select-Options S_MTART for G_MTART Obligatory.
Selection-Screen End Of Line.

* Select Options: S_MATKL
Selection-Screen Begin Of Line.
Selection-Screen Comment 2(22) text-006.
Select-Options S_MATKL for G_MATKL Obligatory.
Selection-Screen End Of Line.

* Select Options: S_MATNR
Selection-Screen Begin Of Line.
Selection-Screen Comment 2(22) text-008.
Select-Options S_MATNR for G_MATNR.
Selection-Screen End Of Line.

Selection-Screen End Of Block A.

Selection-Screen Begin Of Block H With Frame Title text-010.

* Parameter: ALV Display Variant
Selection-Screen Begin Of Line.
Selection-Screen Comment 2(25) text-011.
Parameter P_alvv type DISVARIANT-VARIANT.
Selection-Screen End Of Line.

Selection-Screen End Of Block H.

*$*$--------------------------------------------------------------------
*$*$ INITIALIZATION Event
*$*$--------------------------------------------------------------------
Initialization.

* Get default variant for ALV
  WA_variant-report = sy-repid.
  Call Function 'REUSE_ALV_VARIANT_DEFAULT_GET'
    EXPORTING
      I_SAVE     = 'A'
    CHANGING
      CS_VARIANT = WA_variant
    EXCEPTIONS
      NOT_FOUND  = 2.
  IF SY-SUBRC = 0.
    P_alvv = WA_VARIANT-VARIANT.
  ENDIF.

*$*$--------------------------------------------------------------------
*$*$  AT SELECTION SCREEN ON Event
*$*$--------------------------------------------------------------------

*$*$ Validate Plant
At Selection-Screen ON S_WERKS.
  Perform Validate_WERKS.

*$*$ Validate Material type
At Selection-Screen ON S_MTART.
  Perform Validate_MTART.

*$*$ Validate Material group
At Selection-Screen ON S_MATKL.
  Perform Validate_MATKL.

*$*$ Validate Material number
At Selection-Screen ON S_MATNR.
  Perform Validate_MATNR.

*$*$ Validate ALV Display Variant
At Selection-Screen ON P_alvv.
* Check the existence of Variant
  perform alv_variant_check using WA_variant P_alvv.

*$*$ F4 help on Screen field P_ALVV
At Selection-Screen ON Value-Request for P_ALVV.
  Perform f4_for_variant using WA_variant P_ALVV.

*$*$--------------------------------------------------------------------
*$*$ TOP OF PAGE Event
*$*$--------------------------------------------------------------------
TOP-OF-PAGE.
* Subroutine for Top of Page event.
* perform top_of_page.

*$*$--------------------------------------------------------------------
*$*$ END OF PAGE Event
*$*$--------------------------------------------------------------------
end-of-page.
* Subroutine for End of Page event.
* perform end_of_page.

*$*$--------------------------------------------------------------------
*$*$ START OF SELECTION Event
*$*$--------------------------------------------------------------------
Start-Of-Selection.

* Perform selects and populate internal tables
  Perform LOAD_INTERNAL_TABLES.

* Process the internal table table
  Perform PROCESS_DATA.

* Populate the final output table for display
  Perform FINAL_STATISTICS.

*$*$--------------------------------------------------------------------
*$*$  END OF SELECTION Event
*$*$--------------------------------------------------------------------
END-OF-SELECTION.

* Display the report output using ALV
  Perform WRITE_REPORT.

*$*$--------------------------------------------------------------------
*$*$ Form Validate_WERKS
*$*$--------------------------------------------------------------------
FORM VALIDATE_WERKS.

  Data L_WERKS type T001W-WERKS.

* Check for initial value before validating
  Check not S_WERKS is initial.

* Select Plant for validation
  SELECT WERKS UP TO 1 ROWS
  From T001W Into L_WERKS
  Where WERKS in S_WERKS.
  Endselect.

* Stop processing and issue error message in case of error
  If sy-subrc ne 0.
    Message e398(00) with 'Incorrect entry for'(e02)
                   'Plant'(003) space space.
  Endif.

Endform. " FORM VALIDATE_WERKS

*$*$--------------------------------------------------------------------
*$*$ Form Validate_MTART
*$*$--------------------------------------------------------------------
FORM VALIDATE_MTART.

  Data L_MTART type T134-MTART.

* Check for initial value before validating
  Check not S_MTART is initial.

* Select Material type for validation
  SELECT MTART UP TO 1 ROWS
  From T134 Into L_MTART
  Where MTART in S_MTART.
  Endselect.

* Stop processing and issue error message in case of error
  If sy-subrc ne 0.
    Message e398(00) with 'Incorrect entry for'(e02)
                   'Material type'(005) space space.
  Endif.

Endform. " FORM VALIDATE_MTART

*$*$--------------------------------------------------------------------
*$*$ Form Validate_MATKL
*$*$--------------------------------------------------------------------
FORM VALIDATE_MATKL.

  Data L_MATKL type T023-MATKL.

* Check for initial value before validating
  Check not S_MATKL is initial.

* Select Material group for validation
  SELECT MATKL UP TO 1 ROWS
  From T023 Into L_MATKL
  Where MATKL in S_MATKL.
  Endselect.

* Stop processing and issue error message in case of error
  If sy-subrc ne 0.
    Message e398(00) with 'Incorrect entry for'(e02)
                   'Material group'(007) space space.
  Endif.

Endform. " FORM VALIDATE_MATKL

*$*$--------------------------------------------------------------------
*$*$ Form Validate_MATNR
*$*$--------------------------------------------------------------------
FORM VALIDATE_MATNR.

  Data L_MATNR type MARA-MATNR.

* Check for initial value before validating
  Check not S_MATNR is initial.

* Select Material number for validation
  SELECT MATNR UP TO 1 ROWS
  From MARA Into L_MATNR
  Where MATNR in S_MATNR.
  Endselect.

* Stop processing and issue error message in case of error
  If sy-subrc ne 0.
    Message e398(00) with 'Incorrect entry for'(e02)
                   'Material number'(009) space space.
  Endif.

Endform. " FORM VALIDATE_MATNR

*$*$--------------------------------------------------------------------
*$*$ Form LOAD_INTERNAL_TABLES
*$*$--------------------------------------------------------------------
FORM LOAD_INTERNAL_TABLES.

* Select data from table MARC MARA MAKT
  Perform select_MARC_MARA_MAKT.

* Select data from table KNA1
  Perform select_data_KNA1.

Endform. " FORM LOAD_INTERNAL_TABLES

*$*$--------------------------------------------------------------------
*$*$ Form SELECT_MARC_MARA_MAKT
*$*$--------------------------------------------------------------------
FORM SELECT_MARC_MARA_MAKT.

* Select data from table
  SELECT MARC~WERKS
         MARC~MATNR
         MARC~PRCTR
         MARC~DISLS
         MARC~BESKZ
         MARC~FXHOR
         MARA~MTART
         MARA~MATKL
         MAKT~MAKTX
    From MARC
    Join MARA
      ON MARC~MATNR eq MARA~MATNR
    Join MAKT
      ON MARA~MATNR eq MAKT~MATNR
    Into table I_MARC_MARA_MAKT
   Where MARC~WERKS in S_WERKS                    "Plant
     And MARA~MTART in S_MTART                    "Material Type
     And MARA~MATKL in S_MATKL                    "Material Group
     And MARA~MATNR in S_MATNR.                   "testMaterial

* Issue error message if the select fails
  if sy-subrc ne 0.
    Message i398(00) with 'No data selected from table'(e03)
              'MARC'(012) 'MARA'(013) 'MAKT'(014).
    Leave list-processing.
  endif.

endform. " FORM SELECT_MARC_MARA_MAKT

*$*$--------------------------------------------------------------------
*$*$ Form SELECT_DATA_KNA1
*$*$--------------------------------------------------------------------
FORM SELECT_DATA_KNA1.

* Select data from table
  SELECT KUNNR
    From KNA1
    Into table I_KNA1.

* Issue error message if the select fails
  if sy-subrc ne 0.
    Message i398(00) with 'No data selected from table'(e03)
              'KNA1'(015) space space.
    Leave list-processing.
  endif.

endform. " FORM SELECT_DATA_KNA1

*$*$--------------------------------------------------------------------
*$*$ Form PROCESS_DATA
*$*$--------------------------------------------------------------------
FORM PROCESS_DATA.

* Populate data into final output internal table
  Loop at I_KNA1 into WA_KNA1.
* WA_outdata-WERKS =
* WA_outdata-MATKL =
* WA_outdata-PRCTR =
* WA_outdata-MTART =
* WA_outdata-MATNR =
* WA_outdata-MAKTX =
* WA_outdata-DISLS =
* WA_outdata-BESKZ =
* WA_outdata-FXHOR =

    Append WA_outdata to I_outdata.

  ENDLOOP. " LOOP AT I_KNA1

Endform. " FORM PROCESS_DATA

*$*$--------------------------------------------------------------------
*$*$ Form FINAL_STATISTICS
*$*$--------------------------------------------------------------------
FORM FINAL_STATISTICS.

Endform. " FORM FINAL_STATISTICS

*$*$--------------------------------------------------------------------
*$*$ Form WRITE_REPORT
*$*$--------------------------------------------------------------------
FORM WRITE_REPORT.

* Write the final report depending on error or success
  If not I_errors[] is initial.

* Write Report Header
    Perform write_report_header
                   Using 'Company code description'
                         'prog short description'
                         'prog description'.

* Write Error Report
    Perform write_error_report TABLES I_errors.

* Else write the report data
  Else.

* If no ALV output is required
    If I_outdata[] is initial.

* Write Report Header
      Perform write_report_header
                     Using 'Company code description'
                           'prog short description'
                           'prog description'.

******* Add your own custom message here for display
    else.

* Write report header
      Perform write_alv_header Using I_alv_header[]
                                     'prog short description'.

* Prepare layout for the ALV display
      Perform prepare_layout USING WA_layout
                                   c_check    "Column Optimize
                                   space      "No Column Heading
                                   c_check    "Zebra layout
                                   space      "No Vertical line
                                   space      "No Key Fix
                                   c_check    "No Input
                                   space      "Window Titlebar
                                   space      "No Sumchoice
                                   space      "No total line
                                   space      "No subchoice
                                   space      "No subtotals
                                   space      "Totals only
                                   space      "Totals text
                                   space      "No scrolling
                                   space      "Detail popup
                                   space.     "Detail Titlebar

* Prepare Event table for the ALV display
      Perform populate_events Tables I_event
                               Using C_ALV_EVENTS-TOP_OF_PAGE
                                    'TOP_OF_PAGE'.

* Prepare field catalog for the ALV display
      Perform create_fieldcatalog.

* Display report output
      Perform display_report TABLES I_outdata
                              Using sy-cprog          "Callback program
                                    WA_layout         "Display layout
                                    I_fieldcat        "Field Catalog
                                    I_sortcat         "Sort details
                                    C_check           "Variant(A, ,U,X)
                                    WA_variant        "Display Variant
                                    I_event           "Events
                                    'I_outdata'       "Output itab name
                                    space.            "List/Grid display

    Endif.
  endif.

ENDFORM. " FORM WRITE_REPORT

*$*$--------------------------------------------------------------------
*$*$ Form CREATE_FIELDCATALOG
*$*$--------------------------------------------------------------------
FORM CREATE_FIELDCATALOG.

  Perform build_fieldcat_tab Tables I_fieldcat using:
  'I_OUTDATA' 'WERKS' ' ' 'MARC' ' ' ' ' 'PLANT'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'MATKL' ' ' 'MARA' ' ' ' ' 'MATERIAL GROUP'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'PRCTR' ' ' 'MARC' ' ' ' ' 'PROFIT CENTER'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'MTART' ' ' 'MARA' ' ' ' ' 'MATERIAL TYPE'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'MATNR' ' ' 'MARA' ' ' ' ' 'MATERIAL NUMBER'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'MAKTX' ' ' 'MAKT' ' ' ' ' 'MAT DESCRIPTION'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'DISLS' ' ' 'MARC' ' ' ' ' 'LOT SIZE'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'BESKZ' ' ' 'MARC' ' ' ' ' 'PROCUREMENT TYP'
                      ' ' ' ' ' ' 'L',
  'I_OUTDATA' 'FXHOR' ' ' 'MARC' ' ' ' ' 'PLANNING TIME'
                      ' ' ' ' ' ' 'L'.

ENDFORM. " FORM CREATE_FIELDCATALOG

*$*$--------------------------------------------------------------------
*$*$ Form TOP_OF_PAGE
*$*$--------------------------------------------------------------------
FORM TOP_OF_PAGE.

* Call the ALV function module for header top of page
  CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'
    EXPORTING
      it_list_commentary = I_alv_header.

ENDFORM. " FORM TOP_OF_PAGE

*$*$--------------------------------------------------------------------
*$*$ Form END_OF_PAGE
*$*$--------------------------------------------------------------------
FORM END_OF_PAGE.

** Write the logic for any End of Page display here

ENDFORM. " FORM END_OF_PAGE

*Text elements
*----------------------------------------------------------
* 001 Selection Parameters
* 002 Plant
* 003 Plant
* 004 Material type
* 005 Material type
* 006 Material group
* 007 Material group
* 008 Material number
* 009 Material number
* 010 ALV Variant
* 011 ALV Display Variant
* 012 MARC
* 013 MARA
* 014 MAKT
* 015 KNA1
* E02 Incorrect entry for
* E03 No data selected from table

*Messages
*----------------------------------------------------------
*
* Message class: 00
*398   & & & &

************************************************************************
*&  Include           ZCOMMON_FORMS
************************************************************************

*Text elements
*----------------------------------------------------------
* 001 Selection Parameters
* 002 Plant
* 003 Plant
* 004 Material type
* 005 Material type
* 006 Material group
* 007 Material group
* 008 Material number
* 009 Material number
* 010 ALV Variant
* 011 ALV Display Variant
* 012 MARC
* 013 MARA
* 014 MAKT
* 015 KNA1

*Selection texts
*----------------------------------------------------------
* P_ALVV         Display Variant
* S_MATKL         Material Group
* S_MATNR         Material
* S_MTART         Material Type
* S_WERKS         Plant

*Messages
*----------------------------------------------------------
*
* Message class: 00
*398   & & & &

--------------------------------------------------------------------------------

Code listing for: ZCOMMON_FORMS
Description: Include ZCOMMON_FORMS
--------------------------------------------------------------------------------

************************************************************************
*&  Include           ZCOMMON_FORMS
************************************************************************

* TYPE POOLS
TYPE-POOLS : slis,
             kkblo.

* FIELD-SYMBOLS.
FIELD-SYMBOLS:  TYPE ANY,        "Field Symbol 1
                TYPE ANY,        "Field Symbol 2
                TYPE ANY,
                TYPE ANY.

TYPES tab_epsfili TYPE STANDARD TABLE OF epsfili.

*&---------------------------------------------------------------------*
*&      Form F4_LOCAL_UPLOADFILE
*&---------------------------------------------------------------------*
*       This form provides the F4 file navigator on Selection screen
*----------------------------------------------------------------------*
*       Called by.: Calling Programs
*----------------------------------------------------------------------*
*       Parameters: Filepath --> Return value after navigation
*----------------------------------------------------------------------*
FORM f4_local_uploadfile USING filepath TYPE rlgrap-filename.

  DATA l_rc          TYPE i.
  DATA l_filetab     TYPE filetable.
  DATA l_filetab_wa  TYPE file_table.
  DATA l_title       TYPE string.

  l_title = 'Select local file'(i01).
  CALL METHOD cl_gui_frontend_services=>file_open_dialog
    EXPORTING
      window_title            = l_title
      file_filter             = ',.,..'
      initial_directory       = 'C:\'
    CHANGING
      file_table              = l_filetab
      rc                      = l_rc
    EXCEPTIONS
      file_open_dialog_failed = 1
      cntl_error              = 2
      error_no_gui            = 3
      not_supported_by_gui    = 4
      OTHERS                  = 5.

  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
               WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ELSE.
    READ TABLE l_filetab INTO l_filetab_wa INDEX 1.
    IF sy-subrc EQ 0.
      filepath = l_filetab_wa-filename.
    ENDIF.
  ENDIF.

ENDFORM.                   " F4_LOCAL_UPLOADFILE

*&---------------------------------------------------------------------*
*&      Form F4_LOCAL_DOWNLOADFILE
*&---------------------------------------------------------------------*
*       This form provides the F4 file navigator on Selection screen
*----------------------------------------------------------------------*
*       Called by.: Calling Programs
*----------------------------------------------------------------------*
*       Parameters: Filepath --> Return value after navigation
*----------------------------------------------------------------------*
FORM f4_local_downloadfile USING filepath TYPE rlgrap-filename.

  DATA l_title       TYPE string.
  DATA l_filename    TYPE string.
  DATA l_filepath    TYPE string.
  DATA l_fullpath    TYPE string.

  l_title = 'Select local file'(i01).
  CALL METHOD cl_gui_frontend_services=>file_save_dialog
    EXPORTING
      window_title         = l_title
      file_filter          = ',.,..'
      initial_directory    = 'C:\'
      prompt_on_overwrite  = 'X'
    CHANGING
      filename             = l_filename
      path                 = l_filepath
      fullpath             = l_fullpath
    EXCEPTIONS
      cntl_error           = 1
      error_no_gui         = 2
      not_supported_by_gui = 3
      OTHERS               = 4.

  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
               WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ELSE.
    filepath = l_fullpath.
  ENDIF.

ENDFORM.                    "f4_local_downloadfile

*&---------------------------------------------------------------------*
*&      Form  F4_APP_UPLOADFILE
*&---------------------------------------------------------------------*
*          Get a navigator for filename on the application server
*----------------------------------------------------------------------*
*            -->P_DIR  Directory Path
*       <--P_FILE File NamE
*----------------------------------------------------------------------*
FORM f4_app_uploadfile USING dir TYPE rlgrap-filename
     file TYPE rlgrap-filename.

* If not DIR path provided is initial
  CHECK NOT dir IS INITIAL.

  CALL FUNCTION 'F4_FILENAME_SERVER'
    EXPORTING
      pfad              = dir
    EXCEPTIONS
      no_file_on_server = 1
      OTHERS            = 2.

  IF sy-subrc EQ 0.
    file = sy-lisel+2(68).           "Filename
    CONDENSE file.
  ENDIF.

ENDFORM.                    " F4_APP_UPLOADFILE

*---------------------------------------------------------------------*
*       FORM F4_FOR_VARIANT                                           *
*---------------------------------------------------------------------*
*       F4 help for the Layout variant names in ALV display
*---------------------------------------------------------------------*
FORM f4_for_variant USING p_wa_variant TYPE any
                          p_layout     TYPE any.

  DATA l_exit(1) TYPE c.
  DATA l_wa_variant TYPE disvariant.

  CALL FUNCTION 'REUSE_ALV_VARIANT_F4'
    EXPORTING
      is_variant = p_wa_variant
      i_save     = 'A'
    IMPORTING
      e_exit     = l_exit
      es_variant = l_wa_variant
    EXCEPTIONS
      not_found  = 2.

  IF sy-subrc EQ 0.
    IF l_exit = space.
      p_layout = l_wa_variant-variant.
    ENDIF.
  ENDIF.

ENDFORM.                    "F4_FOR_VARIANT

*&---------------------------------------------------------------------*
*&      Form  build_filename
*&---------------------------------------------------------------------*
*       Build the complete file path from Directory and Path and
*       Pass back as one variable
*----------------------------------------------------------------------*
*       ---> DIR   Directory path
*       ---> PATH  File path
*       ---> FULL_PATH  Full Path
*----------------------------------------------------------------------*
FORM build_filename   USING dir       TYPE rlgrap-filename
                            path      TYPE rlgrap-filename
                            full_path TYPE any.

* Check if the Directory path has got a '/' at the end and add if not
  PERFORM format_directory USING dir.

* Build up the full file path
  CONCATENATE dir path INTO full_path.

ENDFORM.                    "build_filename

*&---------------------------------------------------------------------*
*&      Form  format_directory
*&---------------------------------------------------------------------*
*       Format the directory path from the selection screen and
* adds a slash at the end (if available/not available)
*----------------------------------------------------------------------*
*       ---> p_dir  Directory path
*----------------------------------------------------------------------*
FORM format_directory USING p_dir TYPE rlgrap-filename.

  DATA l_dir_length TYPE  i VALUE 0.
  DATA l_dir_length_less_1 TYPE  i VALUE 0.

* Check last character of directory is '/'
  l_dir_length = STRLEN( p_dir ).

  l_dir_length_less_1 = l_dir_length - 1.

  IF p_dir+l_dir_length_less_1(1) NE '/'.

    CONCATENATE  p_dir
                 '/'
           INTO  p_dir.

  ENDIF.

ENDFORM.                    "format_directory

*&---------------------------------------------------------------------*
*  Form: READ_APPFILE
*&---------------------------------------------------------------------*
*  This subroutine is used for reading the application server file
*  and then splitting the file data into the internal table structure
*  of the program
*----------------------------------------------------------------------*
*  Parameters: <-- FILE_STRUCTURE: Itab for storing infile data
*              <-- RETURN:  Error table
*              --> FILENAME: File name
*              --> SEPARATOR:  File separator
*&---------------------------------------------------------------------*
FORM read_appfile TABLES file_intab
                         return     TYPE tt_bapiret2
                  USING  filename   TYPE any
                         separator  TYPE any.

*  DATA wa_file type line of file_intab.

* Temporary table structure for storing data after splitting
  TYPES: BEGIN OF l_ty_source_data,
             fieldval(150)  TYPE c,            "File contents
         END OF l_ty_source_data.

* Structure of the file for storing the data read
  TYPES: BEGIN OF l_ty_file,
             text(500)  TYPE c,                "File contents
         END  OF l_ty_file.

* Internal table and Workarea structure for storing data after splitting
  DATA l_i_source_data TYPE STANDARD TABLE OF
                          l_ty_source_data INITIAL SIZE 0.
  DATA l_wa_source_data TYPE l_ty_source_data.

* Internal table and work area for storing the data read from file
  DATA l_i_file TYPE STANDARD TABLE OF l_ty_file INITIAL SIZE 0.
  DATA l_wa_file TYPE l_ty_file.

* Opens the file for reading
  OPEN DATASET filename FOR INPUT IN TEXT MODE ENCODING DEFAULT.

* File Open failed
  IF sy-subrc NE 0.
    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to open file'(i02)
                                   filename
                                  'for reading'(i03)
                                   space.
    EXIT.

  ENDIF.

  DO.

*   Read the current record of the source file
    READ DATASET filename INTO l_wa_file.
    IF sy-subrc EQ 4.
      EXIT.
    ENDIF.

    APPEND l_wa_file TO l_i_file .

  ENDDO.

* If the file has a separator
  IF separator NE space.

* Loop at file data and split into the internal table structure
    LOOP AT l_i_file INTO l_wa_file.

* Split file data at the separator
      SPLIT l_wa_file AT separator INTO TABLE l_i_source_data.

      LOOP AT l_i_source_data INTO l_wa_source_data.
        ASSIGN l_wa_source_data-fieldval TO .
        ASSIGN COMPONENT sy-tabix OF STRUCTURE file_intab TO .
         = .
      ENDLOOP.

      ASSIGN file_intab TO .
      APPEND  TO file_intab.
      UNASSIGN .
    ENDLOOP.

* No file separator
  ELSE.
    file_intab[] = l_i_file[].
  ENDIF.

* Closes the file
  CLOSE DATASET filename.
* Error handling not reqd for closing

ENDFORM.                    "READ_APPFILE

*&---------------------------------------------------------------------*
*  Form: READ_LOCALFILE
*&---------------------------------------------------------------------*
*  This subroutine is used to read a local file and return the internal
*  table with file data
*----------------------------------------------------------------------
*  Parameters: <-- FILE_INTAB: Internal table for storing infile data
*              <-- RETURN:  Error table
*              --> FILENAME: File name
*              --> SEPARATOR:  File separator
*&---------------------------------------------------------------------*
FORM read_localfile  TABLES file_intab
                            return     TYPE tt_bapiret2
                     USING  filename   TYPE any
                            separator  TYPE any.

* Temporary table structure for storing data after splitting
  TYPES: BEGIN OF l_ty_source_data,
             fieldval(150)  TYPE c,        "File contents
         END OF l_ty_source_data.

* Structure of the file for storing the data read
  TYPES: BEGIN OF l_ty_file,
             text(500)  TYPE c,                "File contents
         END  OF l_ty_file.

* Internal table and Workarea structure for storing data after splitting
  DATA l_i_source_data TYPE STANDARD TABLE OF
                                l_ty_source_data INITIAL SIZE 0.
  DATA l_wa_source_data TYPE l_ty_source_data.

* Internal table and work area for storing the data read from file
  DATA l_i_file TYPE STANDARD TABLE OF l_ty_file INITIAL SIZE 0.
  DATA l_wa_file TYPE l_ty_file.

  DATA l_error_msg(40) TYPE c.        "Error Message
  DATA l_filename TYPE string.

* Change the filename to a FM compatible type
  l_filename = filename.

* Read file from presentation layer
  CALL FUNCTION 'GUI_UPLOAD'
    EXPORTING
      filename                = l_filename
    TABLES
      data_tab                = l_i_file
    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.

* File Open failed
  IF sy-subrc NE 0.

* Get the exact error parameter for the failure
    SELECT parameter FROM fupararef UP TO 1 ROWS
      INTO l_error_msg
     WHERE funcname EQ 'GUI_UPLOAD'
       AND r3state EQ 'A'              "Active
       AND paramtype EQ 'X'            "Exception
       AND pposition EQ sy-subrc.
    ENDSELECT.

    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to open file'(i02)
                                   filename
                                  'for reading. Error:'(i40)
                                   l_error_msg.
    EXIT.

  ENDIF.

* If the file has a separator
  IF separator NE space.
* Loop at file data and split into the internal table structure
    LOOP AT l_i_file INTO l_wa_file.

      SPLIT l_wa_file AT separator INTO TABLE l_i_source_data.

      LOOP AT l_i_source_data INTO l_wa_source_data.
        ASSIGN l_wa_source_data-fieldval TO .
        ASSIGN COMPONENT sy-tabix OF STRUCTURE file_intab TO .
         = .
      ENDLOOP.
      ASSIGN file_intab TO .
      APPEND  TO file_intab.
      UNASSIGN .

    ENDLOOP.

* No file separator
  ELSE.
    file_intab[] = l_i_file[].
  ENDIF.

ENDFORM.  "READ_LOCALFILE

*&---------------------------------------------------------------------*
*  Form: WRITE_LOCALFILE
*&---------------------------------------------------------------------*
*  This subroutine is used to write a local file
*&---------------------------------------------------------------------*
*  Parameters: <-- FILE_OUTTAB : Internal table containing download data
*              <-- RETURN:    Error table
*              --> FILENAME:  File name
*              --> SEPARATOR: File separator
*&---------------------------------------------------------------------*
FORM write_localfile TABLES file_outtab
                            return       TYPE tt_bapiret2
                     USING  filename     TYPE any
                            separator    TYPE any.

  DATA l_error_msg(40) TYPE c.        "Error Message
  DATA l_filename TYPE string.

* Internal table for storing the structure fields with seperator.
  TYPES  l_v_text(2500) TYPE c.
  DATA   l_i_text TYPE STANDARD TABLE OF l_v_text
                          INITIAL SIZE 0.  "SR with header line.

* Final string containing structure fields with seperator
  DATA: l_raw_data LIKE LINE OF l_i_text,
        l_max_field LIKE l_raw_data,
        l_len_separator TYPE i,         "Length of seperator
        l_start_string TYPE i,
        l_len_string TYPE i,
        l_column_index LIKE sy-index.

* Change the filename to a FM compatible type
  l_filename = filename.

* Add separator in the file if required
  IF separator NE space.   "No separator, fixed length file

    CLEAR: l_i_text.
    REFRESH: l_i_text.

    l_len_separator = STRLEN( separator ).

** If you output table contains any decimals (type P, Quan, Curr etc),
** then convert them into character fields and pass an output table
** containing all character fields. This i believe is standard practice
    LOOP AT file_outtab ASSIGNING .
      file_outtab = .

      CLEAR: l_column_index, l_raw_data, l_start_string.

      DO.
        l_column_index = l_column_index + 1.
        CLEAR l_len_string.
        ASSIGN COMPONENT l_column_index OF
                 STRUCTURE file_outtab TO .
        IF sy-subrc <> 0.
          EXIT.
        ELSE.

          IF l_column_index <> 1.
            l_max_field+l_len_string(l_len_separator) = separator.
            l_len_string = l_len_separator.
          ENDIF.

          l_max_field+l_len_string = .
*       check the remaining space of target structure
          l_len_string = STRLEN( l_max_field ).
          CHECK l_len_string <> 0.
          l_raw_data+l_start_string(l_len_string) = l_max_field.
          l_start_string = l_start_string + l_len_string.
        ENDIF.
      ENDDO.

      IF NOT l_raw_data IS INITIAL.
        APPEND l_raw_data TO l_i_text.
        CLEAR l_raw_data.
      ENDIF.

    ENDLOOP.

* Download the file
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename                = l_filename
      TABLES
        data_tab                = l_i_text
      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.

  ELSE.

* Download the file without any separators
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename                = l_filename
      TABLES
        data_tab                = file_outtab
      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.

  ENDIF.

* Report any errors

  IF sy-subrc NE 0.
* Get the exact error parameter for the failure
    SELECT parameter FROM fupararef UP TO 1 ROWS
      INTO l_error_msg
     WHERE funcname EQ 'GUI_DOWNLOAD'
       AND r3state EQ 'A'              "Active
       AND paramtype EQ 'X'            "Exception
       AND pposition EQ sy-subrc.
    ENDSELECT.

    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to download file'(i04)
                                   filename
                                  'Error:'(i05)
                                   l_error_msg.
    EXIT.
  ENDIF.

ENDFORM.  "WRITE_LOCALFILE

*&---------------------------------------------------------------------*
*  Form: WRITE_APPFILE
*&---------------------------------------------------------------------*
*  This subroutine is used to write a local file
*&---------------------------------------------------------------------*
*  Parameters: <-- FILE_OUTTAB: Internal table containing download data
*              <-- RETURN:    Error table
*              --> FILENAME:  File name
*              --> SEPARATOR: File separator
*&---------------------------------------------------------------------*
FORM write_appfile TABLES file_outtab
                          return       TYPE tt_bapiret2
                   USING  filename     TYPE any
                          separator    TYPE any.

*Internal table for storing the structure fields with seperator.
  TYPES  l_v_text(2500) TYPE c.
  DATA   l_i_text TYPE STANDARD TABLE OF l_v_text
                          INITIAL SIZE 0. "SR with header line.

* Final string containing structure fields with seperator
  DATA: l_raw_data LIKE LINE OF l_i_text,
        l_max_field LIKE l_raw_data,
        l_len_separator TYPE i,         "Length of seperator
        l_start_string TYPE i,
        l_len_string TYPE i,
        l_column_index LIKE sy-index,
        l_msg(50) TYPE c.                "Error message

  CLEAR: l_i_text.
  REFRESH: l_i_text.

* Write file to app server with required separators
  IF separator NE space.   "No separator, fixed length file

    l_len_separator = STRLEN( separator ).

** If you output table contains any decimals (type P, Quan, Curr etc),
** then convert them into character fields and pass an output table
** containing all character fields. This i believe is standard practice
    LOOP AT file_outtab ASSIGNING .
      file_outtab = .

      CLEAR: l_column_index, l_raw_data, l_start_string.

      DO.
        l_column_index = l_column_index + 1.
        CLEAR l_len_string.
        ASSIGN COMPONENT l_column_index OF
                 STRUCTURE file_outtab TO .
        IF sy-subrc <> 0.
          EXIT.
        ELSE.

          IF l_column_index <> 1.
            l_max_field+l_len_string(l_len_separator) = separator.
            l_len_string = l_len_separator.
          ENDIF.

          l_max_field+l_len_string = .
*       check the remaining space of target structure
          l_len_string = STRLEN( l_max_field ).
          CHECK l_len_string <> 0.

          l_raw_data+l_start_string(l_len_string) = l_max_field.
          l_start_string = l_start_string + l_len_string.
        ENDIF.
      ENDDO.

      IF NOT l_raw_data IS INITIAL.
        APPEND l_raw_data TO l_i_text.
        CLEAR l_raw_data.
      ENDIF.

    ENDLOOP.

  ENDIF.

* Write dataset on app server
  OPEN DATASET filename FOR OUTPUT IN TEXT MODE
                            ENCODING DEFAULT MESSAGE l_msg.

* Report any errors for file creation
  IF sy-subrc NE 0.
    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
            'Error creating file on the application server'(i06)
                                   filename
                                   'Error:'(i05)
                                   l_msg.
    EXIT.
  ENDIF.

  IF NOT l_i_text[] IS INITIAL.
    LOOP AT l_i_text INTO l_raw_data.
      TRANSFER l_raw_data TO filename.
    ENDLOOP.
  ELSE.
    LOOP AT file_outtab ASSIGNING .
      file_outtab = .
      TRANSFER file_outtab TO filename.
    ENDLOOP.
  ENDIF.

* Close file
  CLOSE DATASET filename.

ENDFORM.            "WRITE_APPFILE

*&---------------------------------------------------------------------*
*  Form: MESSAGE_BUILD
*&---------------------------------------------------------------------*
*  This subroutine is used populate the messages in return structure
*&---------------------------------------------------------------------*
*  Parameters:  <--RETURN: Error table with message
*               -->CLASS:  Message Class
*               -->TYPE:   Message Type
*               -->NUMBER: Message Number
*               -->VAR1:   Message Variable 1
*               -->VAR2:   Message Variable 2
*               -->VAR3:   Message Variable 3
*               -->VAR4:   Message Variable 4
***********************************************************************
FORM message_build TABLES return           TYPE tt_bapiret2
                   USING  value(class)     TYPE symsgid
                          value(type)      TYPE symsgty
                          value(number)    TYPE symsgno
                          value(var1)      TYPE any
                          value(var2)      TYPE any
                          value(var3)      TYPE any
                          value(var4)      TYPE any.

  DATA: ld_par1   TYPE symsgv,                "Variable for Msg
        ld_par2   TYPE symsgv,                "Variable for Msg
        ld_par3   TYPE symsgv,                "Variable for Msg
        ld_par4   TYPE symsgv,                "Variable for Msg
        ls_return TYPE bapiret2.              "Return structure

* Assign Message to variables
  ld_par1 = var1.
  ld_par2 = var2.
  ld_par3 = var3.
  ld_par4 = var4.

* Fills the return parameter
  CALL FUNCTION 'BALW_BAPIRETURN_GET2'
    EXPORTING
      type   = type
      cl     = class
      number = number
      par1   = ld_par1
      par2   = ld_par2
      par3   = ld_par3
      par4   = ld_par4
    IMPORTING
      return = ls_return.

  APPEND ls_return TO return.

ENDFORM.                    "MESSAGE_BUILD

*&---------------------------------------------------------------------*
*&      Form  bdcdynpro
*&---------------------------------------------------------------------*
*       This form inserts a screen call into the bdcdata table
*----------------------------------------------------------------------*
*       Parameters: --> PROG_NAME
*                       SCREEN_NO
*----------------------------------------------------------------------*
FORM bdcdynpro TABLES bdcdata   TYPE tab_bdcdata
               USING  prog_name TYPE bdcdata-program
                      screen_no TYPE bdcdata-dynpro.

  DATA  l_wa_bdcdata    LIKE bdcdata.

  l_wa_bdcdata-program  = prog_name.            " Program name
  l_wa_bdcdata-dynpro   = screen_no.            " Screen Number
  l_wa_bdcdata-dynbegin = 'X'.                  " X

* Append bdc table and clear work area
  APPEND l_wa_bdcdata TO bdcdata.

ENDFORM.                " BDCDYNPRO

*&---------------------------------------------------------------------*
*&      Form BDCFIELD
*&---------------------------------------------------------------------*
*       This form fills the bdcdata table with the data required to
*       populate a field.
*----------------------------------------------------------------------*
*       Called by.: Calling Programs
*----------------------------------------------------------------------*
*       Parameters: --> F_NAM                        " Field name
*                       F_VAL                        " Field value
*----------------------------------------------------------------------*
FORM bdcfield TABLES bdcdata TYPE tab_bdcdata
              USING  f_nam   TYPE any
                     f_val   TYPE any.

  DATA  l_wa_bdcdata    LIKE bdcdata.

* Fill the fields in the dynpro called with the correct values
  l_wa_bdcdata-fnam = f_nam.                            " Field Name
  l_wa_bdcdata-fval = f_val.                            " Field Value

* Append bdc table and clear work area.
  APPEND l_wa_bdcdata TO bdcdata.
  CLEAR  l_wa_bdcdata.

ENDFORM.                                             " BDCFIELD

*&---------------------------------------------------------------------*
*&      Form  CALL_TRANSACTION
*&---------------------------------------------------------------------*
*       This routine performs a CALL TRANSACTION statement             *
*----------------------------------------------------------------------*
*      -->BDC_MESSAGES     Table for BDC return messages
*      -->T_CODE           Transaction that is called
*      -->INPUT_METHOD     Method A/E/N
*      -->UPDATE_METHOD    Update method (A/S)
*----------------------------------------------------------------------*
FORM call_transaction     TABLES   bdc_messages TYPE tab_bdcmsgcoll
                                   bdcdata      TYPE tab_bdcdata
                                   return       TYPE tt_bapiret2
                          USING    t_code       TYPE any
                                   input_method TYPE any
                                   update_method TYPE any.

  DATA l_bdc_messages TYPE bdcmsgcoll.
  DATA l_msgno(3) TYPE n.

  CLEAR bdc_messages.
  REFRESH bdc_messages.

  CALL TRANSACTION t_code USING    bdcdata
                          MODE     input_method
                          UPDATE   update_method
                          MESSAGES INTO bdc_messages.

* Add error handling logic and add populate Return table
* Report any errors for file creation
  IF sy-subrc NE 0.
    LOOP AT bdc_messages INTO l_bdc_messages WHERE ( msgtyp EQ 'E'
                                                  OR msgtyp EQ 'A' ).

      l_msgno = l_bdc_messages-msgnr.
      PERFORM message_build TABLES  return
                             USING  l_bdc_messages-msgid
                                    l_bdc_messages-msgtyp
                                    l_msgno
                                    l_bdc_messages-msgv1
                                    l_bdc_messages-msgv2
                                    l_bdc_messages-msgv3
                                    l_bdc_messages-msgv4.
    ENDLOOP.
  ENDIF.

ENDFORM.                           " CALL_TRANSACTION

*----------------------------------------------------------------------*
*  Form: OPEN_BDC_SESSION
*----------------------------------------------------------------------*
*  This subroutine is used to open the BDC session
*----------------------------------------------------------------------*
*  PARAMETERS:   <--RETURN: Error Table
*                -->SESSION: Session Name
*----------------------------------------------------------------------*
FORM open_bdc_session   TABLES return  TYPE tt_bapiret2
                        USING  session TYPE  apq_grpn.

  DATA l_error_msg(40) TYPE c.        "Error Message

  CALL FUNCTION 'BDC_OPEN_GROUP'
    EXPORTING
      client              = sy-mandt
      group               = session
      keep                = 'X'
      user                = sy-uname
    EXCEPTIONS
      client_invalid      = 1
      destination_invalid = 2
      group_invalid       = 3
      group_is_locked     = 4
      holddate_invalid    = 5
      internal_error      = 6
      queue_error         = 7
      running             = 8
      system_lock_error   = 9
      user_invalid        = 10
      OTHERS              = 11.

  IF sy-subrc NE 0.
* Get the exact error parameter for the failure
    SELECT parameter FROM fupararef UP TO 1 ROWS
      INTO l_error_msg
     WHERE funcname EQ 'BDC_OPEN_GROUP'
       AND r3state  EQ 'A'             "Active
       AND paramtype EQ 'X'            "Exception
       AND pposition EQ sy-subrc.
    ENDSELECT.

    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to Open Session'(i07)
                                   session
                                  'Error:'(i05)
                                   l_error_msg.
    EXIT.
  ENDIF.

ENDFORM.    "OPEN_BDC_SESSION

*----------------------------------------------------------------------*
*  Form: INSERT_BDC_TAB
*----------------------------------------------------------------------*
*  This subroutine is used to insert BDC session record
*----------------------------------------------------------------------*
*  PARAMETERS:  <-- RETURN: Error Table
*               --> TCODE:  Transaction Code
*----------------------------------------------------------------------*
FORM insert_bdc_tab  TABLES  bdcdata TYPE tab_bdcdata
                             return  TYPE tt_bapiret2
                     USING   tcode   TYPE      tcode.

  DATA l_error_msg(40) TYPE c.        "Error Message

* Inserting into the BDC table
  CALL FUNCTION 'BDC_INSERT'
    EXPORTING
      tcode            = tcode
    TABLES
      dynprotab        = bdcdata
    EXCEPTIONS
      internal_error   = 1
      not_open         = 2
      queue_error      = 3
      tcode_invalid    = 4
      printing_invalid = 5
      posting_invalid  = 6
      OTHERS           = 7.

  IF sy-subrc NE 0.
* Get the exact error parameter for the failure
    SELECT parameter FROM fupararef UP TO 1 ROWS
      INTO l_error_msg
     WHERE funcname EQ 'BDC_INSERT'
       AND r3state  EQ 'A'             "Active
       AND paramtype EQ 'X'            "Exception
       AND pposition EQ sy-subrc.
    ENDSELECT.

    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to Insert Session'(i08)
                                  'Error:'(i05)
                                   l_error_msg
                                   space.
    EXIT.
  ENDIF.

ENDFORM.      "INSERT_BDC_TAB

*----------------------------------------------------------------------*
*  Form: CLOSE_BDC_TAB
*----------------------------------------------------------------------*
*  This subroutine is used to close the BDC session
*----------------------------------------------------------------------*
*  PARAMETERS:  <-- RETURN: Error Table
*               -->SESSION: Session Name
*----------------------------------------------------------------------*
FORM close_bdc_tab TABLES return TYPE tt_bapiret2
                    USING session  TYPE any.

* Close the current batch input session
  CALL FUNCTION 'BDC_CLOSE_GROUP'
    EXCEPTIONS
      not_open    = 1
      queue_error = 2
      OTHERS      = 3.

* If BDC session closing fails
  IF sy-subrc NE 0.
    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to close BDC session:'(i09)
                                   session
                                   space
                                   space.
  ENDIF.

ENDFORM.      "CLOSE_BDC_TAB

*&---------------------------------------------------------------------*
*&      Form  ALV_VARIANT_CHECK
*&---------------------------------------------------------------------*
*     Check the existence of ALV Variant and populate the variant table
*----------------------------------------------------------------------*
FORM alv_variant_check USING p_wa_variant TYPE disvariant
                             p_layout  TYPE any.

  DATA l_wa_variant TYPE disvariant.

* If a layout has been entered on the screen, then validate the same
  IF NOT p_layout IS INITIAL.

    MOVE p_wa_variant TO l_wa_variant.
    MOVE p_layout TO l_wa_variant-variant.

    CALL FUNCTION 'REUSE_ALV_VARIANT_EXISTENCE'
      EXPORTING
        i_save     = 'A'
      CHANGING
        cs_variant = l_wa_variant.
    p_wa_variant = l_wa_variant.

  ELSE.
    p_wa_variant-report = sy-cprog.
  ENDIF.

ENDFORM.                               " ALV_VARIANT_CHECK

*&---------------------------------------------------------------------*
*&      Form  write_report_header
*&---------------------------------------------------------------------*
*       Create the report header
*----------------------------------------------------------------------*
*       Parameters:  --> P_TEXT1: Company Code Description
*                    --> P_TEXT2: Report Description 1
*                    --> P_TEXT3: Report Description 2
*----------------------------------------------------------------------*
FORM write_report_header USING  p_text1  TYPE any
                                p_text2  TYPE any
                                p_text3  TYPE any.

  CONSTANTS: c_hyphen(1)   TYPE c VALUE '-'.   " Hyphen

  DATA: l_pagno(5)   TYPE c,         " Page no
        l_page_len   TYPE p,         " String length of page no
        l_name_len   TYPE p,         " String length of company name
        l_hdr1_len   TYPE p,         " String length of header line 1
        l_hdr2_len   TYPE p,         " String length of header line 2
        l_line1_pos  TYPE p,         " Printing pos of company name
        l_line2_pos  TYPE p,         " Printing pos of header line 1
        l_line3_pos  TYPE p,         " Printing pos of header line 2
        l_right_pos1 TYPE p,         " Position from right margin
        l_right_pos2 TYPE p,         " Position from right margin
        l_center     TYPE p.         " Center of page

* Calculate string lengths and printing positions
  l_name_len = STRLEN( p_text1 ).
  l_hdr1_len = STRLEN( p_text2 ).
  l_hdr2_len = STRLEN( p_text3 ).

  l_center = ( sy-linsz / 2 ).

  l_line1_pos = l_center - ( l_name_len / 2 ).
  l_line2_pos = l_center - ( l_hdr1_len / 2 ).
  l_line3_pos = l_center - ( l_hdr2_len / 2 ).

  l_right_pos1 = sy-linsz - 10.
  l_right_pos2 = sy-linsz - 16.

  FORMAT COLOR COL_HEADING.

* Write 1st line of report header--------------------------------------*
  WRITE: 'Program:'(i00).
  WRITE 9 sy-repid.

  WRITE: AT l_line1_pos  p_text1,
         AT l_right_pos2 'Page:'(i38).

  POSITION l_right_pos1.
* Left justify the page number
  l_pagno = sy-pagno.
  SHIFT l_pagno LEFT DELETING LEADING space.

  l_page_len = STRLEN( l_pagno ).

  IF l_page_len > 3.
    WRITE (12) l_pagno USING EDIT MASK ',__'.
  ELSE.
    WRITE (12) l_pagno.
  ENDIF.

* Write 2nd line of report header--------------------------------------*
  WRITE:/ 'System:'(i39), AT 9  sy-sysid,
                          AT 12 c_hyphen,
                          AT 13 sy-mandt.

  WRITE: AT l_line2_pos p_text2,
         AT l_right_pos2 'Date:'(i13).

  POSITION l_right_pos1.
  WRITE (11) sy-datum.

* Write 3rd line of report header--------------------------------------*
  WRITE:/ 'UserID:'(i20), AT 9 sy-uname.

  WRITE: AT l_line3_pos p_text3,
         AT l_right_pos2 'Time:'(i28).

  POSITION l_right_pos1.
  WRITE (11) sy-uzeit.

  FORMAT COLOR OFF.

  ULINE.

ENDFORM.                    " write_report_header

*&---------------------------------------------------------------------*
*&      Form  write_alv_header
*&---------------------------------------------------------------------*
*       Create the report header for ALV
*----------------------------------------------------------------------*
*       Parameters:  --> P_TEXT1: Program Description
*----------------------------------------------------------------------*
FORM write_alv_header USING p_i_alv_header TYPE slis_t_listheader
                            p_text1        TYPE any.

  CONSTANTS: c_hyphen(1)   TYPE c VALUE '-'.   " Hyphen
  DATA  l_wa_alv_header    TYPE slis_listheader.

* Title for ALV
  l_wa_alv_header-typ  = 'H'.
  l_wa_alv_header-info = p_text1.
  APPEND l_wa_alv_header TO p_i_alv_header.
  CLEAR l_wa_alv_header.

* First detail
  l_wa_alv_header-typ   = 'S'.
  l_wa_alv_header-key   = 'Program:'(i10).
  l_wa_alv_header-info  = sy-repid.
  l_wa_alv_header-info+42  = 'System:'(i11).
  l_wa_alv_header-info+50  = sy-sysid.
  l_wa_alv_header-info+53  = c_hyphen.
  l_wa_alv_header-info+54  = sy-mandt.
  APPEND l_wa_alv_header TO p_i_alv_header.
  CLEAR l_wa_alv_header.

* Second Detail
  l_wa_alv_header-typ  = 'S'.
  l_wa_alv_header-key   = 'User ID:'(i12).
  l_wa_alv_header-info =  sy-uname.
  l_wa_alv_header-info+22  = 'Date:'(i13).
  l_wa_alv_header-info+28  = sy-datum.
  l_wa_alv_header-info+42  = 'Time:'(i14).
  l_wa_alv_header-info+47  = sy-uzeit.
  APPEND l_wa_alv_header TO p_i_alv_header.
  CLEAR l_wa_alv_header.

ENDFORM.                    " write_alv_header

*&--------------------------------------------------------------------*
*&      Form  WRITE_ERROR_REPORT
*&--------------------------------------------------------------------*
*       Format the Error report
*---------------------------------------------------------------------*
*  PARAMETERS:  --> I_ERRORS: Error Table
*----------------------------------------------------------------------*
FORM write_error_report TABLES i_errors TYPE tt_bapiret2.

* Internal table and Work area for Selection table
  DATA  l_it_seltab  TYPE  TABLE OF rsparams INITIAL SIZE 0.

* Program name
  DATA l_repid TYPE sy-repid.
  DATA l_message(100) TYPE c.
  DATA l_wa_errors TYPE bapiret2.

  l_repid = sy-cprog.

* This function module selects the selection Screen contents
  CALL FUNCTION 'RS_REFRESH_FROM_SELECTOPTIONS'
    EXPORTING
      curr_report     = l_repid
    TABLES
      selection_table = l_it_seltab
    EXCEPTIONS
      not_found       = 1
      no_report       = 2
      OTHERS          = 3.
  IF sy-subrc EQ 0.
    WRITE:1  'Selection Criteria'(i21),
         /1  sy-uline(18),
         /1  'Variant Name'(i22),
         23  sy-slset.

* This function module lists the Selection Screen contents
    CALL FUNCTION 'RS_LIST_SELECTION_TABLE'
      EXPORTING
        report        = l_repid
        seltext       = 'X'
        newpage       = space
      TABLES
        sel_tab       = l_it_seltab
      EXCEPTIONS
        sel_tab_empty = 1
        OTHERS        = 2.
    IF sy-subrc <> 0.
*     Error handling
    ENDIF.
  ENDIF.

* End of Page
  SKIP 1.
  FORMAT COLOR OFF INTENSIFIED ON.

  SKIP 2.
  WRITE: / 'Error Report'(i23),
         / '------------'.
  SKIP.

*     Output all errors detected.
  ULINE AT /(120).
  FORMAT COLOR COL_HEADING.
  WRITE: / sy-vline, 'Msg Class'(i24), 20 sy-vline, 'Msg Number'(i25),
        40 sy-vline, 'Error Message'(i26).
  WRITE AT 120 sy-vline.
  ULINE AT /(120).

  FORMAT RESET.

* Display data Error
  LOOP AT i_errors INTO l_wa_errors.
    FORMAT INTENSIFIED ON.

* Get text for the message
    CALL FUNCTION 'FORMAT_MESSAGE'
      EXPORTING
        id        = l_wa_errors-id
        lang      = sy-langu
        no        = l_wa_errors-number
        v1        = l_wa_errors-message_v1
        v2        = l_wa_errors-message_v2
        v3        = l_wa_errors-message_v3
        v4        = l_wa_errors-message_v4
      IMPORTING
        msg       = l_message
      EXCEPTIONS
        not_found = 1
        OTHERS    = 2.
    IF sy-subrc <> 0.
*     Error handling
    ENDIF.

    SHIFT l_message LEFT DELETING LEADING space.
    WRITE: / sy-vline, l_wa_errors-id, 20 sy-vline, l_wa_errors-number,
          40 sy-vline, 41 l_message.
    WRITE AT 120 sy-vline.

  ENDLOOP.

  ULINE AT /(120).

  SKIP 2.

  WRITE :/60 '** End of Report **'(i27).

ENDFORM.                    "write_error_report

*&---------------------------------------------------------------------*
*&      Form  prepare_layout
*&---------------------------------------------------------------------*
*   Prepare the Layout of the Report Output List
*----------------------------------------------------------------------*
*      -->P_WA_LAYOUT             " Layout structure
*      -->P_NO_COLHEAD            " No Column Headings
*      -->P_ZEBRA                 " Stripped Pattern
*      -->P_NO_VLINE              " Columns Separated by Space
*      -->P_NO_KEYFIX             " Do not fix key fields
*      -->P_NO_INPUT              " Display fields only
*      -->P_WINDOW_TITLEBAR       " Title of List
*      -->P_NO_SUMCHOICE          " No Summation Choice
*      -->P_NO_TOTALLINE          " Do not show total Line
*      -->P_NO_SUBCHOICE          " No Subtotal Choice
*      -->P_NO_SUBTOTALS          " Do not Show Subtotals
*      -->P_TOTALS_ONLY           " Show Totals only
*      -->P_TOTALS_TEXT           " Totals Text
*      -->P_NO_SCROLLING          " Allow no scrolling
*      -->P_DETAIL_POPUP          " Show details in a Popup
*      -->P_DETAIL_TITLEBAR       " Tile for the Detail window
*----------------------------------------------------------------------*
FORM prepare_layout USING    p_wa_layout     TYPE slis_layout_alv
                             p_col_optimize  TYPE any
                             p_no_colhead    TYPE any
                             p_zebra         TYPE any
                             p_no_vline      TYPE any
                             p_no_keyfix     TYPE any
                             p_no_input      TYPE any
                             p_window_titlebar TYPE any
                             p_no_sumchoice  TYPE any
                             p_no_totalline  TYPE any
                             p_no_subchoice  TYPE any
                             p_no_subtotals  TYPE any
                             p_totals_only   TYPE any
                             p_totals_text   TYPE any
                             p_no_scrolling  TYPE any
                             p_detail_popup  TYPE any
                             p_detail_titlebar TYPE any.

  p_wa_layout-colwidth_optimize        = p_col_optimize.
  p_wa_layout-no_colhead               = p_no_colhead.
  p_wa_layout-zebra                    = p_zebra.
  p_wa_layout-no_vline                 = p_no_vline.
  p_wa_layout-no_keyfix                = p_no_keyfix.
  p_wa_layout-no_input                 = p_no_input.
  p_wa_layout-window_titlebar          = p_window_titlebar.
  p_wa_layout-no_sumchoice             = p_no_sumchoice.
  p_wa_layout-no_totalline             = p_no_totalline.
  p_wa_layout-no_subchoice             = p_no_subchoice.
  p_wa_layout-no_subtotals             = p_no_subtotals.
  p_wa_layout-totals_only              = p_totals_only.
  p_wa_layout-totals_text              = p_totals_text.
  p_wa_layout-no_scrolling             = p_no_scrolling.
  p_wa_layout-detail_popup             = p_detail_popup.
  p_wa_layout-detail_titlebar          = p_detail_titlebar.

ENDFORM.                    " prepare_layout

*&---------------------------------------------------------------------*
*      Form build_fieldcat_tab
*&---------------------------------------------------------------------*
*    This subroutine is used to build the field catalog table for
*    generating an ALV report
*----------------------------------------------------------------------*
*    Parameters:
*    tablename       --> Internal Table Name
*    fieldname       --> Internal Table Field Name
*    key             --> (X or space) to declare field as key
*    referencetable  --> Reference table
*    outputactive    --> Output active
*    col_posn        --> Cloumn Position
*    col_hdng        --> Column heading
*    datatype        --> Data Type
*    outputlen       --> Length of output
*    description     --> Desciption text
*    justification   --> Justification of output L, R etc
*----------------------------------------------------------------------*
FORM build_fieldcat_tab TABLES    p_i_fieldcatalog
                         USING    tablename      TYPE any
                                  fieldname      TYPE any
                                  key            TYPE any
                                  referencetable TYPE any
                                  outputactive   TYPE any
                                  col_posn       TYPE any
                                  col_hdng       TYPE any
                                  datatype       TYPE any
                                  outputlen      TYPE any
                                  description    TYPE any
                                  justification  TYPE any.

  DATA l_fieldcat TYPE slis_fieldcat_alv.

  l_fieldcat-tabname        = tablename.     " Internal Table Name
  l_fieldcat-fieldname      = fieldname.     " Internal Table Field Name
  l_fieldcat-key            = key. "(X or space) to declare field as key
  l_fieldcat-ref_tabname    = referencetable. " Reference table
  l_fieldcat-no_out         = outputactive.   " Output active
  l_fieldcat-col_pos        = col_posn.       " Cloumn Position
  l_fieldcat-reptext_ddic   = col_hdng.       " Column heading
  l_fieldcat-datatype       = datatype.       " Data Type
  l_fieldcat-outputlen      = outputlen.      " Length of output
  l_fieldcat-seltext_m      = description.    " Desciption text
  l_fieldcat-just           = justification.  " Justification

  APPEND l_fieldcat TO p_i_fieldcatalog.

ENDFORM.                    " build_fieldcat_tab

*&---------------------------------------------------------------------*
*&      Form  populate_events
*&---------------------------------------------------------------------*
*     Populate events for the ALV report
*----------------------------------------------------------------------*
*      -->P_NAME  Name of the Event
*      -->P_FORM  Name of the Subroutine to handle the Event
*----------------------------------------------------------------------*
FORM populate_events TABLES   p_i_event
                     USING    p_name       TYPE any
                              p_form       TYPE any.

  DATA  l_wa_event TYPE slis_alv_event.

  l_wa_event-name          = p_name.
  l_wa_event-form          = p_form.
  APPEND l_wa_event TO p_i_event.

ENDFORM.                    " populate_events

*&---------------------------------------------------------------------*
*&      Form  alv_eventtab_build
*&---------------------------------------------------------------------*
*       Event BUild
*The events table returned by this subroutine should be passed
*while calling the function module for list display
*----------------------------------------------------------------------*
*      -->P_C_TOP_OF_PAGE    TOP OF PAGE
*      -->P_C_END_OF_LIST    END OF LIST
*      <--P_IT_EVENTS[]      EVENTS
*----------------------------------------------------------------------*
FORM alv_eventtab_build USING    id_top_of_page TYPE slis_formname
                                 id_end_of_list TYPE slis_formname
                        CHANGING ct_event TYPE slis_t_event.

  DATA: ls_event TYPE slis_alv_event.

  REFRESH ct_event.

  CALL FUNCTION 'REUSE_ALV_EVENTS_GET'
    EXPORTING
      i_list_type = 0
    IMPORTING
      et_events   = ct_event.

* top of page
  READ TABLE ct_event WITH KEY name = slis_ev_top_of_page
                                        INTO ls_event.
  IF sy-subrc = 0.
    MOVE id_top_of_page TO ls_event-form.
    MODIFY ct_event FROM ls_event INDEX sy-tabix.
  ENDIF.

* end of list
  READ TABLE ct_event WITH KEY name = slis_ev_end_of_list
                                        INTO ls_event.
  IF sy-subrc = 0.
    MOVE id_end_of_list TO ls_event-form.
    MODIFY ct_event FROM ls_event INDEX sy-tabix.
  ENDIF.

ENDFORM.                               " ALV_EVENTTAB_BUILD

*&---------------------------------------------------------------------*
*&      Form  add_sort_field
*&---------------------------------------------------------------------*
*        Add a Field to the Sort Catalog
*----------------------------------------------------------------------*
*      -->P_SPOS              " Sort Postion
*      -->P_FIELDNAME         " Sort Field
*      -->P_TABNAME           " Sort Table
*      -->P_UP                " Sort Ascending
*      -->P_DOWN              " Sort Descending
*      -->P_SUBTOT            " Sobtotal on the Field
*----------------------------------------------------------------------*
FORM add_sort_field TABLES   p_i_sortcatalog
                    USING    p_spos          TYPE any
                             p_fieldname     TYPE any
                             p_tabname       TYPE any
                             p_up            TYPE any
                             p_down          TYPE any
                             p_subtot        TYPE any.

* Internal table and Work area for ALV field Sort Catalog
  DATA  l_wa_sortcat TYPE slis_sortinfo_alv  .

  l_wa_sortcat-spos          = p_spos.
  l_wa_sortcat-fieldname     = p_fieldname.
  l_wa_sortcat-tabname       = p_tabname.
  l_wa_sortcat-up            = p_up.
  l_wa_sortcat-down          = p_down.
  l_wa_sortcat-subtot        = p_subtot.
  APPEND l_wa_sortcat TO p_i_sortcatalog.

ENDFORM.                    " add_sort_field

*&---------------------------------------------------------------------*
*&      Form  display_report
*&---------------------------------------------------------------------*
*   Call the ALV Interface to Display the Report Output List
*----------------------------------------------------------------------*
*      -->P_I_OUTTAB                  " Output List Internal Table
*      -->P_I_CALLBACK_PROGRAM        " Callback Program name
*      -->P_IS_LAYOUT                 " Layout Defination
*      -->P_IT_FIELDCAT               " Field Catalog
*      -->P_IT_SORT                   " Sort Catalog
*      -->P_SAVE                      " Allow saving of User Variants
*      -->P_IS_VARIANT                " Variant Name
*      -->P_IT_EVENTS                 " List Events
*      -->P_FLAG                      " Flag determine LIST/GRID display
*----------------------------------------------------------------------*
FORM display_report TABLES   p_i_outtab
                     USING   value(p_i_callback_program) TYPE any
                             p_is_layout        TYPE any
                             p_it_fieldcat      TYPE any
                             p_it_sort          TYPE any
                             p_save             TYPE any
                             p_is_variant       TYPE any
                             p_it_events        TYPE any
                             p_itabname         TYPE any
                             p_flag             TYPE any.

  DATA l_tabname(30) TYPE c.
  l_tabname = p_itabname.
  TRANSLATE l_tabname TO UPPER CASE.

* Merge field characteristics from Dictionary
  CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
      i_program_name     = p_i_callback_program
      i_internal_tabname = l_tabname
      i_inclname         = p_i_callback_program
    CHANGING
      ct_fieldcat        = p_it_fieldcat.

  IF p_flag EQ 'X'.         "ALV List display

    CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
      EXPORTING
        i_callback_program = p_i_callback_program
        is_layout          = p_is_layout
        it_fieldcat        = p_it_fieldcat
        it_sort            = p_it_sort
        i_save             = p_save
        is_variant         = p_is_variant
        it_events          = p_it_events
      TABLES
        t_outtab           = p_i_outtab
      EXCEPTIONS
        program_error      = 1
        OTHERS             = 2.
    IF sy-subrc NE 0.
*     Error handling
    ENDIF.

  ELSE.

* ALV Grid display
    CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
      EXPORTING
        i_callback_program = p_i_callback_program
        is_layout          = p_is_layout
        it_fieldcat        = p_it_fieldcat
        it_sort            = p_it_sort
        i_save             = p_save
        is_variant         = p_is_variant
        it_events          = p_it_events
      TABLES
        t_outtab           = p_i_outtab
      EXCEPTIONS
        program_error      = 1
        OTHERS             = 2.
    IF sy-subrc NE 0.
*     Error handling
    ENDIF.

  ENDIF.

ENDFORM.                    " display_report

*&----------------------------------------------------------------------
*  Form: POPULATE_CONTROL_RECORD
*&----------------------------------------------------------------------
*    This subroutine is used to create the control record for IDOC
*-----------------------------------------------------------------------
FORM populate_control_record USING p_wa_edidc TYPE edidc
                                   p_msgtype  TYPE any
                                   p_idoctype TYPE any
                                   p_rcvprt   TYPE any
                                   p_rcvprn   TYPE any
                                   p_rcvpor   TYPE any
                                   p_sndprt   TYPE any
                                   p_sndprn   TYPE any
                                   p_sndpor   TYPE any.

* Populate the control record for the IDoc
  p_wa_edidc-doctyp = p_idoctype.
  p_wa_edidc-mestyp  = p_msgtype.
  p_wa_edidc-sndpor  = p_sndpor.
  p_wa_edidc-sndprt  = p_sndprt.
  p_wa_edidc-sndprn  = p_sndprn.
  p_wa_edidc-rcvprt  = p_rcvprt.
  p_wa_edidc-rcvprn  = p_rcvprn.
  p_wa_edidc-rcvpor  = p_rcvpor.

ENDFORM.                    "POPULATE_CONTROL_RECORD

*&----------------------------------------------------------------------
*  Form: CREATE_IDOC_OUTBOUND
*&----------------------------------------------------------------------
*      This subroutine is used to create Outbound IDoc
*-----------------------------------------------------------------------
FORM create_idoc_outbound TABLES p_i_edidd TYPE edidd_tt
                                 return
                           USING p_wa_edidc TYPE edidc.

  DATA l_error_msg(40) TYPE c.        "Error Message
  DATA l_i_edidc TYPE STANDARD TABLE OF edidc INITIAL SIZE 0.

  APPEND p_wa_edidc TO l_i_edidc.

* Call standard SAP Function module to create Idocs
  CALL FUNCTION 'MASTER_IDOC_DISTRIBUTE'
    EXPORTING
      master_idoc_control            = p_wa_edidc
    TABLES
      communication_idoc_control     = l_i_edidc
      master_idoc_data               = p_i_edidd
    EXCEPTIONS
      error_in_idoc_control          = 1
      error_writing_idoc_status      = 2
      error_in_idoc_data             = 3
      sending_logical_system_unknown = 4
      OTHERS                         = 5.

  IF sy-subrc EQ 0.
    COMMIT WORK.

  ELSE.

* Get the exact error parameter for the failure
    SELECT parameter FROM fupararef UP TO 1 ROWS
      INTO l_error_msg
     WHERE funcname EQ 'MASTER_IDOC_DISTRIBUTE'
       AND r3state  EQ 'A'             "Active
       AND paramtype EQ 'X'            "Exception
       AND pposition EQ sy-subrc.
    ENDSELECT.

    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to Create IDoc'(i15)
                                  'Error:'(i05)
                                   l_error_msg
                                   space.
    EXIT.
  ENDIF.

* Clear Work Area
  REFRESH: p_i_edidd.

ENDFORM.                    "create_idoc_outbound

*&---------------------------------------------------------------------*
*  Form: CREATE_IDOC_INBOUND
*&---------------------------------------------------------------------*
*      This subroutine is used to create inbound idocs
*----------------------------------------------------------------------*
FORM create_idoc_inbound  TABLES p_i_edidd   TYPE edi_dd40_tt
                                 return
                           USING p_wa_edidc  TYPE edidc
                        CHANGING idoc_number TYPE edi_docnum.

  DATA l_edidc TYPE edi_dc40.

  MOVE-CORRESPONDING p_wa_edidc TO l_edidc.
  l_edidc-idoctyp = p_wa_edidc-doctyp.

* Call function to create IDoc
  CALL FUNCTION 'IDOC_INBOUND_SINGLE'
    EXPORTING
      pi_idoc_control_rec_40  = l_edidc
    IMPORTING
      pe_idoc_number          = idoc_number
    TABLES
      pt_idoc_data_records_40 = p_i_edidd
    EXCEPTIONS
      idoc_not_saved          = 1
      OTHERS                  = 2.

  IF sy-subrc NE 0.
    PERFORM message_build TABLES  return
                           USING  '00'
                                  'E'
                                  '398'
                                  'Unable to Create Inbound IDoc'(i16)
                                   space
                                   space
                                   space.
    EXIT.
  ENDIF.

* Clear Work Area
  REFRESH: p_i_edidd.

ENDFORM.                    "create_idoc_inbound

*&---------------------------------------------------------------------*
*&      Form  convert_dec_to_user_setting
*&---------------------------------------------------------------------*
*       Convert currency value according to user setting eg, decimal
*       separator, thousand separator etc.
*----------------------------------------------------------------------*
*       <-> L_VALUE External Value
*----------------------------------------------------------------------*
FORM conv_decima_user_setting CHANGING l_value TYPE any.

  DATA: l_dcpfm TYPE xudcpfm. "Decimal notation

  SELECT SINGLE dcpfm         "Decimal format
  FROM usr01
  INTO (l_dcpfm)
  WHERE bname = sy-uname.

  IF sy-subrc = 0.
*   Decimal Formatting
    IF l_dcpfm = 'X'.
* Do nothing
    ELSE.
      REPLACE ALL OCCURRENCES OF ',' IN l_value WITH space.
      CONDENSE l_value.
      REPLACE '.' IN l_value WITH ','.
    ENDIF.
  ENDIF.

ENDFORM.                    "convert_decimal_to_user_setting

*&--------------------------------------------------------------------*
*&      Form  convert_date_to_user_setting
*&--------------------------------------------------------------------*
*       Format the date according to the user setting for the user
*       mentioned in the BDC session
*---------------------------------------------------------------------*
*       <-> L_VALUE date in format YYYYMMDD
*       Comment: L_VALUE should be a CHAR10 variable.You need to take
*                the date field to a CHAR10 variable and pass the
*                CHAR10 variable to this perform to convert it to
*                user format.
*---------------------------------------------------------------------*
FORM convert_date_to_user_setting CHANGING l_value TYPE any.

  DATA: l_datfm TYPE c,                    " of type xudatfm
        l_date  TYPE sydatum.

  SELECT SINGLE datfm
  INTO (l_datfm)
  FROM usr01
  WHERE bname = sy-uname.

  IF sy-subrc = 0.

    CASE l_datfm.

      WHEN '1'.                       "DD.MM.YYYY format

        l_date = l_value.
        CONCATENATE l_date+6(2)       "DD
                    l_date+4(2)       "MM
                    l_date+0(4)       "YYYY
        INTO l_value
        SEPARATED BY '.'.

      WHEN '2'.

        l_date = l_value.             "MM/DD/YYYY format
        CONCATENATE l_date+4(2)       "MM
                    l_date+6(2)       "DD
                    l_date+0(4)       "YYYY
        INTO l_value
        SEPARATED BY '/'.

      WHEN '3'.

        l_date = l_value.             "MM-DD-YYYY format
        CONCATENATE l_date+4(2)       "MM
                    l_date+6(2)       "DD
                    l_date+0(4)       "YYYY
        INTO l_value
        SEPARATED BY '-'.

      WHEN '4'.

        l_date = l_value.             "YYYY.MM.DD format
        CONCATENATE l_date+0(4)       "YYYY
                    l_date+4(2)       "MM
                    l_date+6(2)       "DD
        INTO l_value
        SEPARATED BY '.'.

      WHEN '5'.

        l_date = l_value.             "YYYY/MM/DD format
        CONCATENATE l_date+0(4)       "YYYY
                    l_date+4(2)       "MM
                    l_date+6(2)       "DD
        INTO l_value
        SEPARATED BY '/'.

      WHEN '6'.

        l_date = l_value.             "YYYY-MM-DD format
        CONCATENATE l_date+0(4)       "YYYY
                    l_date+4(2)       "MM
                    l_date+6(2)       "DD
        INTO l_value
        SEPARATED BY '-'.

      WHEN OTHERS.
    ENDCASE.
  ENDIF.

ENDFORM.                    "convert_date_to_user_setting

*&--------------------------------------------------------------------*
*&      Form  numeric_check
*&--------------------------------------------------------------------*
*       Checks if the string contains non-numeric character
*---------------------------------------------------------------------*
*      --> L_FIELD    Field name
*      --> L_VALUE    Value of the field
*      --> L_TABIX    Record Index
*      --> L_DEC      Decimal Check flag
*      <-- RETURNS    Error Table
*---------------------------------------------------------------------*
FORM numeric_check TABLES return TYPE tt_bapiret2
                   USING  l_field  TYPE any
                          l_value  TYPE any
                          l_tabix  TYPE any
                          l_dec    TYPE any.

  CONSTANTS c_number_string(11)
        TYPE c VALUE '0123456789 '. "Numbers only
  CONSTANTS c_numeric_string(12)
        TYPE c VALUE '0123456789. '."Numeric characters
  DATA l_message(50) TYPE c.

* If the decimal check is 'X' then
* If the field value is non-numeric then raise error
  IF l_dec = 'X'.

    IF l_value CN c_numeric_string.                         "0-9.SPACE
      CONCATENATE 'Field:'(i17) l_field 'Value:'(i18) l_value
      'Index:'(i19) l_tabix
      'should be numeric'
      INTO l_message SEPARATED BY space.
      PERFORM message_build TABLES  return
                             USING  '00'
                                    'E'
                                    '398'
                                     l_message
                                     space
                                     space
                                     space.
    ENDIF.

  ELSE.
    IF l_value CN c_number_string.                          "0-9 SPACE
      CONCATENATE 'Field:'(i17) l_field 'Value:'(i18) l_value
      'Index:'(i19) l_tabix
      'should be numeric'
      INTO l_message SEPARATED BY space.
      PERFORM message_build TABLES  return
                             USING  '00'
                                    'E'
                                    '398'
                                     l_message
                                     space
                                     space
                                     space.
    ENDIF.
  ENDIF.

ENDFORM.                    "numeric_check

*&---------------------------------------------------------------------*
*&      Form  convert_material
*&---------------------------------------------------------------------*
*       Convert material number to SAP internal format
*----------------------------------------------------------------------*
*       <-> L_MATNR Material number
*       <-> L_SUBRC Status
*----------------------------------------------------------------------*
FORM convert_material CHANGING p_matnr TYPE any
                               p_subrc TYPE any.

* Call the conversion exit FM for MATNR
  CALL FUNCTION 'CONVERSION_EXIT_MATN1_INPUT'
    EXPORTING
      input        = p_matnr
    IMPORTING
      output       = p_matnr
    EXCEPTIONS
      length_error = 1
      OTHERS       = 2.

  p_subrc = sy-subrc.

ENDFORM.                    "convert_material

*&---------------------------------------------------------------------*
*&      Form  convert_vendor
*&---------------------------------------------------------------------*
*       Convert Vendon number to SAP internal format
*----------------------------------------------------------------------*
*       <-> L_LIFNR Material number
*----------------------------------------------------------------------*
FORM convert_vendor   CHANGING p_lifnr TYPE any.

* Call the conversion exit FM for vendor
  CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
    EXPORTING
      input  = p_lifnr
    IMPORTING
      output = p_lifnr.

ENDFORM.                    "convert_vendor

*&--------------------------------------------------------------------*
*&      Form  convert_uom
*&--------------------------------------------------------------------*
*       Convert Unit of Measure to SAP internal format
*---------------------------------------------------------------------*
*      <-> L_MEINS    Unit of Measure
*      <-> L_SUBRC    Status
*---------------------------------------------------------------------*
FORM convert_uom CHANGING p_meins TYPE any
                          p_subrc TYPE any.

* Call the conversion exit FM for UoM
  CALL FUNCTION 'CONVERSION_EXIT_CUNIT_INPUT'
    EXPORTING
      input          = p_meins
      language       = sy-langu
    IMPORTING
      output         = p_meins
    EXCEPTIONS
      unit_not_found = 1
      OTHERS         = 2.
  p_subrc = sy-subrc.

ENDFORM.                    "convert_uom

*&---------------------------------------------------------------------*
*&       Form  sub_send_mail
*&---------------------------------------------------------------------*
*   Send mails from SAP to SAPuser or internet user
*   Receiver type  is 'B' for SAP user
*                     'U' for Internet user
*                     'C' for distribution list
*----------------------------------------------------------------------*
FORM sub_send_mail TABLES object_header    TYPE srm_t_solisti1
                          object_content   TYPE srm_t_solisti1
                          receivers        TYPE bubas_t_receiver
                   USING  subject_line     TYPE char255
                          receiver_type    TYPE so_escape
                          receiver_address TYPE so_rec_id.

**Declare these tables in your program before using this Subroutine
* Header details for the SAP Mail
*  DATA  i_object_hdr TYPE STANDARD TABLE OF solisti1  INITIAL SIZE 0.
* Body of SAP mail
*  DATA  i_obj_content TYPE STANDARD TABLE OF solisti1  INITIAL SIZE 0.
* Internal table for storing recipients of mail
*  DATA  i_receivers   TYPE STANDARD TABLE OF somlreci1 INITIAL SIZE 0.
**

* Work area for mail recipients
  DATA l_wa_receivers         TYPE somlreci1.
* Work area for sap mail
  DATA  l_wa_object_hd_change TYPE sodocchgi1.

* Set SAPmail header data (object definition & attributes)
  l_wa_object_hd_change-obj_langu  =  sy-langu.
  l_wa_object_hd_change-obj_name   = 'SAP'.
  l_wa_object_hd_change-sensitivty = 'F'.
  l_wa_object_hd_change-obj_descr  = subject_line.

*Populate the receiver data
  l_wa_receivers-receiver = receiver_address.
  l_wa_receivers-rec_type = receiver_type.
  APPEND l_wa_receivers  TO receivers.
  CLEAR l_wa_receivers.

  CALL FUNCTION 'SO_NEW_DOCUMENT_SEND_API1'
    EXPORTING
      document_data              = l_wa_object_hd_change
      document_type              = 'RAW'
      put_in_outbox              = 'X'
      commit_work                = 'X'      " COMMIT for SCOT
    TABLES
      object_header              = object_header
      object_content             = object_content
      receivers                  = receivers
    EXCEPTIONS
      too_many_receivers         = 1
      document_not_sent          = 2
      document_type_not_exist    = 3
      operation_no_authorization = 4
      parameter_error            = 5
      x_error                    = 6
      enqueue_error              = 7
      OTHERS                     = 8.

  IF sy-subrc NE 0.
*  Error handling
  ENDIF.

ENDFORM.                    "sub_send_mail

*&---------------------------------------------------------------------*
*  Form: DIRECTORY_SEARCH
*&---------------------------------------------------------------------*
*  This subroutine is used get the file names from a directory
*----------------------------------------------------------------------*
*  Parameters:   <-- I_GET_FILES - File list
*                --> P_PATH - File path
*                --> P_MASK - File masking/extension
*----------------------------------------------------------------------*
FORM directory_search  TABLES  p_i_get_files TYPE tab_epsfili
                        USING  p_path      TYPE      epsdirnam
                               p_mask      TYPE      epsfilnam.

* Get file names
  CALL FUNCTION 'EPS_GET_DIRECTORY_LISTING'
    EXPORTING
      dir_name               = p_path
      file_mask              = p_mask
    TABLES
      dir_list               = p_i_get_files
    EXCEPTIONS
      invalid_eps_subdir     = 1
      sapgparam_failed       = 2
      build_directory_failed = 3
      no_authorization       = 4
      read_directory_failed  = 5
      too_many_read_errors   = 6
      empty_directory_list   = 7
      OTHERS                 = 8.

  IF sy-subrc NE 0.
*   Error handling
  ENDIF.

ENDFORM.  "F_DIRECTORY_SEARCH

--------------------------------------------------------------------------------

  • No labels