martes, 13 de diciembre de 2011

Funcion para extraer año y periodo de fecha


* Encuentra el periodo actual basado en la fecha actual
*
REPORT ZPERIOD.

DATA: X_PERIOD LIKE T009B-POPER,
      X_YEAR   LIKE CSSL-GJAHR.

CALL FUNCTION 'DATE_TO_PERIOD_CONVERT'
     EXPORTING
          I_DATE         = SY-DATUM
*         I_MONMIT       = 00
          I_PERIV        = 'K4'
     IMPORTING
          E_BUPER        = X_PERIOD
          E_GJAHR        = X_YEAR
     EXCEPTIONS
          INPUT_FALSE    = 1
          T009_NOTFOUND  = 2
          T009B_NOTFOUND = 3
          OTHERS         = 4.

WRITE: / 'El periodo actual de la compañia es:', X_PERIOD, X_YEAR.

miércoles, 19 de octubre de 2011

SET/GET PARAMETER Ejemplo

 
Se utiliza para guardar un valor en memoria y volverlo a leer desde otro codigo.


REPORT  PARAMID                                                 .
 
data: gd_valuein(10) type c,
      gd_valueout(10) type c.
 
PARAMETERS: p_value(10) type c.
 
 
********************
*start-of-selection.
start-of-selection.
get parameter ID 'ZMESS' field gd_valuein.
set parameter ID 'ZMESS' field p_value.
get parameter ID 'ZMESS' field gd_valueout.
 
 
******************
*end-of-selection.
end-of-selection.
write:/ 'value at start of program:',  gd_valuein,
      / 'value at end of program:',  gd_valueout.

lunes, 10 de octubre de 2011

Ciclos (Loops)

Ciclos incondicionales:

DO [n TIMES] ...
[Statement_block]
[statement_block]
ENDDO.
ENDDO.

Además de utilizar el TIMES para restringir el número de pasadas de bucle de n.Utilizar  TIMES para restringir a n el numero de veces que pasa por el ciclo.  Las sentencias EXIT y STOP finalizan el ciclo. El campo del sistema sy-index contiene el numero de ciclos por donde ha pasado.

Ejemplo 1:

DO.
  WRITE sy-index.
SI SY-índice = 3.
   IF sy-index = 3.
EXIT.
         EXIT.
   ENDIF.
ENDDO.ENDDO.

La salida es: 1 2 3.

Ejemplo 2:
DO 2 TIMES.
ESCRIBE SY-índice.
   WRITE sy-index.
SKIP.
   SKIP.
   DO 3 TIMES.
      WRITE sy-index.
ENDDO.
   ENDDO.
SKIP.    SKIP.
 ENDDO.

ENDDO.ENDDO.La salida esLa salida de la lista es la siguiente::
1
1 2 3

2

1 2 3



Ciclos condicionales:

Se repite el ciclo hasta que una condicion sea verdadera.

WHILE log_exp
[Statemaent_block]
[statemaent_block]
ENDWHILE.
ENDWHILE.

Ejemplo:
REPORT demo_flow_control_while.
DATA: length TYPE i VALUE 0,
strl TYPE i VALUE 0,
string(30) TYPE c VALUE 'Test String'.
strl = strlen( string ).

WHILE string NE space.
       WRITE string(1).
       length = sy-index.
       SHIFT string.
ENDWHILE.

WRITE: / 'STRLEN: ', strl.
WRITE: / 'Length of string:', length.

La salida es : T es t S tr ing

STRLEN: 11

Length of String: 11


Terminar un paso de un ciclo incondicionalmente.

Para terminar un único paso de un ciclo utilizar CONTINUE, no ejecuta las sentencias restantes después del CONTINUE y salta al siguiente paso del ciclo.
DO 4 TIMES.
SI SY-índice = 2.
   IF sy-index = 2.
CONTINUE.
          CONTINUE.
ENDIF.
   ENDIF.
ESCRIBE SY-índice.
   WRITE sy-index.
ENDDO.ENDDO.
ENDDO.

La salida es:

1 3 4


Terminar un paso de un ciclo condicionalmente.

Para terminar un paso de un ciclo utilizar CHECK, si la condición no es vardadera cualquier sentencia restante dentro del ciclo es ignorada y continua en el siguiente paso del ciclo.

DO 4 TIMES.
CONSULTAR sy-índice de entre 2 y 3.
   CHECK sy-index BETWEEN 2 and 3.
ESCRIBE SY-índice.
   WRITE sy-index.
ENDDO.ENDDO.

La salida es:
2 3

Salir de un ciclo

Para terminar un cliclo utilizar la sentencia EXIT.
DO 4 TIMES.
SI SY-índice = 3.
   IF sy-index = 3.
EXIT.
          EXIT.
ENDIF.
   ENDIF.
ESCRIBE SY-índice.
ENDDO.  
WRITE sy-index.
ENDDO.ENDDO.
La salida es:
1 2




Funcion completar o quitar ceros a la izquierda

* Función que saca los ceros a la izquierda de una variable
CALL FUNCTION ‘CONVERSION_EXIT_ALPHA_OUTPUT’
EXPORTING
INPUT = VG_VARIABLE
IMPORTING
OUTPUT = VG_VARIABLE.
* Función que completa con ceros a la izquierda de una variable
CALL FUNCTION ‘CONVERSION_EXIT_ALPHA_INPUT’
EXPORTING
INPUT = VG_VARIABLE
IMPORTING
OUTPUT = VG_VARIABLE.

Funcion mayusculas y minusculas

FUNCION TRANSLATE: Convierte un texto a mayusculas o minusculas.

TRANSLATE <texto> TO UPPER CASE.
TRANSLATE <texto> TO LOWER CASE.
TRANSLATE <texto> USING <texto1>.
TRANSLATE <texto> FROM CODE PAGE g1 TO CODE PAGE g2.
TRANSLATE <texto> FROM NUMBER FORMAT n1 TO NUMBER FORMAT n2.

EJEMPLO 1:

DATA TEXTO(6).MOVE 'prueba' TO TEXTO.
TRANSLATE TEXTO TO UPPER CASE.
WRITE TEXTO.


EJEMPLO 2:

DATA: TEXTO(30) VALUE 'ESTO ES UNA PRUEBA',
CAMBIAR
(6) VALUE 'EXBY'.
WRITE TEXTO.
TRANSLATE TEXTO USING CAMBIAR.
WRITE: / TEXTO.


SALIDA:

ESTO ES UNA PRUEBA

XSTO XS UNA PRUXYA

Funcion Sumar Meses a una Fecha

*——————————————————————————-
*LV_DATE_ENT : Fecha de entrada a la que le calculo los meses
*LV_MES: Cantidad de meses que le sumo a LV_DATE_ENT
*LV_DATE_SAL : Fecha que me devuelve la función
*——————————————————————————-
DATALV_DATE_ENT TYPE D,
              LV_MES TYPE i,
              LV_DATE_SAL TYPE D.

LV_DATE_ENT sy-datum.
LV_MES 2.

CALL FUNCTION 'HR_PSD_DATES_ADD_MONTHS'
    EXPORTING
      V_DATE       LV_DATE_ENT
      V_MONTHS     LV_MES
    IMPORTING
      E_DATE       LV_DATE_SAL
    EXCEPTIONS
      NOT_POSITIVE 1
      OTHERS       2.

IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.

Ejemplo:

DATALV_DATE_ENT TYPE D,
       LV_MES TYPE i,
       LV_DATE_SAL TYPE D.

LV_DATE_ENT sy-datum.
LV_MES 10.


CALL FUNCTION 'HR_PSD_DATES_ADD_MONTHS'
    EXPORTING
      V_DATE       LV_DATE_ENT
      V_MONTHS     LV_MES
    IMPORTING
      E_DATE       LV_DATE_SAL
    EXCEPTIONS
      NOT_POSITIVE 1
      OTHERS       2.
  IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
  ENDIF.

miércoles, 28 de septiembre de 2011

Funcion Obtener Año Fiscal Actual

Obtener el año fiscal en curso.

Example:

  CALL FUNCTION 'GET_CURRENT_YEAR'
  EXPORTING
    BUKRS         = '1000'     " Company Code
    DATE          = SY-DATUM   " Date to find fiscal year for
  IMPORTING
    CURRM         = w_currm    " Current Fiscal Month
    CURRY         = w_curry    " Current Fiscal Year
    PREVM         = w_prevm    " Previous Fiscal Month
    PREVY         = w_prevy.  " Previous Fiscal Year

lunes, 26 de septiembre de 2011

BAPI Crear Movimientos Inventario


El siguiente programa ABAP esta hace uso de la función BAPI  BAPI_GOODSMVT_CREATE para realizar el ingreso de materiales para órdenes de compra después de importar los datos desde un sistema externo.


*-------------------------------------------------------------*
* BAPI TO Upload Inventory Data
*
* GMCODE Table T158G - 01 - MB01 - Goods Receipts for Purchase Order
*                      02 - MB31 - Goods Receipts for Prod Order
*                      03 - MB1A - Goods Issue
*                      04 - MB1B - Transfer Posting
*                      05 - MB1C - Enter Other Goods Receipt
*                      06 - MB11
*
* Domain: KZBEW - Movement Indicator
*      Goods movement w/o reference
*  B - Goods movement for purchase order
*  F - Goods movement for production order
*  L - Goods movement for delivery note
*  K - Goods movement for kanban requirement (WM - internal only)
*  O - Subsequent adjustment of "material-provided" consumption
*  W - Subsequent adjustment of proportion/product unit material
*-------------------------------------------------------------*



report zbapi_goodsmovement.

parameters: p-file like rlgrap-filename default
                                 'c:\sapdata\TEST.txt'.

parameters: e-file like rlgrap-filename default
                                 'c:\sapdata\gdsmvterror.txt'.

parameters: xpost like sy-datum default sy-datum.



data: begin of gmhead.
        include structure bapi2017_gm_head_01.
data: end of gmhead.

data: begin of gmcode.
        include structure bapi2017_gm_code.
data: end of gmcode.

data: begin of mthead.
        include structure bapi2017_gm_head_ret.
data: end of mthead.

data: begin of itab occurs 100.
        include structure bapi2017_gm_item_create.
data: end of itab.

data: begin of errmsg occurs 10.
        include structure bapiret2.
data: end of errmsg.

data: wmenge like iseg-menge,
      errflag.

data: begin of pcitab occurs 100,
        ext_doc(10),           "External Document Number
        mvt_type(3),           "Movement Type
        doc_date(8),           "Document Date
        post_date(8),          "Posting Date
        plant(4),              "Plant
        material(18),          "Material Number
        qty(13),               "Quantity
        recv_loc(4),           "Receiving Location
        issue_loc(4),          "Issuing Location
        pur_doc(10),           "Purchase Document No
        po_item(3),            "Purchase Document Item No
        del_no(10),            "Delivery Purchase Order Number
        del_item(3),           "Delivery Item
        prod_doc(10),          "Production Document No
        scrap_reason(10),      "Scrap Reason
        upd_sta(1),            "Update Status
      end of pcitab.



call function 'WS_UPLOAD'
  exporting
    filename                      = p-file
    filetype                      = 'DAT'
* IMPORTING
*   FILELENGTH                    =
  tables
    data_tab                      = pcitab
* EXCEPTIONS
*   FILE_OPEN_ERROR               = 1
*   FILE_READ_ERROR               = 2
*   NO_BATCH                      = 3
*   GUI_REFUSE_FILETRANSFER       = 4
*   INVALID_TYPE                  = 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.
  exit.
endif.



gmhead-pstng_date = sy-datum.
gmhead-doc_date = sy-datum.
gmhead-pr_uname = sy-uname.
gmcode-gm_code = '01'.   "01 - MB01 - Goods Receipts for Purchase Order

loop at pcitab.
  itab-move_type  = pcitab-mvt_type.
  itab-mvt_ind    = 'B'.
  itab-plant      = pcitab-plant.
  itab-material   = pcitab-material.
  itab-entry_qnt  = pcitab-qty.
  itab-move_stloc = pcitab-recv_loc.
  itab-stge_loc   = pcitab-issue_loc.
  itab-po_number  = pcitab-pur_doc.
  itab-po_item    = pcitab-po_item.
  concatenate pcitab-del_no pcitab-del_item into itab-item_text.
  itab-move_reas  = pcitab-scrap_reason.

  append itab.
endloop.


loop at itab.
  write:/ itab-material, itab-plant, itab-stge_loc,
          itab-move_type, itab-entry_qnt, itab-entry_uom,
          itab-entry_uom_iso, itab-po_number, itab-po_item,
                                              pcitab-ext_doc.
endloop.



call function 'BAPI_GOODSMVT_CREATE'
  exporting
    goodsmvt_header             = gmhead
    goodsmvt_code               = gmcode
*   TESTRUN                     = ' '
* IMPORTING
    goodsmvt_headret            = mthead
*   MATERIALDOCUMENT            =
*   MATDOCUMENTYEAR             =
  tables
    goodsmvt_item               = itab
*   GOODSMVT_SERIALNUMBER       =
    return                      = errmsg.

clear errflag.

loop at errmsg.
  if errmsg-type eq 'E'.
    write:/'Error in function', errmsg-message.
    errflag = 'X'.
  else.
    write:/ errmsg-message.
  endif.
endloop.



if errflag is initial.
  commit work and wait.

  if sy-subrc ne 0.
    write:/ 'Error in updating'.
    exit.
  else.
    write:/ mthead-mat_doc, mthead-doc_year.
    perform upd_sta.
  endif.

endif.


*------------------------------------------*
*       FORM UPD_STA                       *
*------------------------------------------*

form upd_sta.
  loop at pcitab.
    pcitab-upd_sta = 'X'.
    modify pcitab.
  endloop.

  call function 'WS_DOWNLOAD'
    exporting
      filename                      = p-file
      filetype                      = 'DAT'
* IMPORTING
*   FILELENGTH                    =
    tables
      data_tab                      = pcitab
* EXCEPTIONS
*   FILE_OPEN_ERROR               = 1
*   FILE_READ_ERROR               = 2
*   NO_BATCH                      = 3
*   GUI_REFUSE_FILETRANSFER       = 4
*   INVALID_TYPE                  = 5
*   OTHERS                        = 6.

endform.