terça-feira, 1 de dezembro de 2026

OData $batch no SAP CPI com Postman, do primeiro MERGE ao lote misto

Publicado originalmente pelo ABHZ

O preço do produto foi gravado. O nome ficou em branco. O Postman mostrou que a chamada chegou ao iFlow, mas ainda faltava descobrir em qual etapa a informação se perdeu.

Esse foi um dos testes que fiz em um laboratório de SAP Cloud Integration (CPI). Neste artigo, você vai montar o mesmo tipo de fluxo, enviar um lote pequeno pelo Postman e evoluir para um lote que consulta, cria, altera e exclui produtos. No final, vou mostrar como encontrei o problema do campo Name.

1. Entenda as duas chamadas

O $batch agrupa várias operações OData em uma única requisição HTTP. Neste cenário, o Postman envia um XML para o endpoint HTTPS do iFlow. O adaptador OData V2 Receiver lê esse XML e monta o POST .../$batch que o serviço OData recebe no formato multipart/mixed.

Fluxo em duas etapas. O Postman envia XML ao iFlow e o adaptador OData V2 envia multipart ao endpoint $batch do serviço.

Essa distinção explica por que a URL do Postman termina em /http/northwind_produtos_merge_batch e por que o seu XML começa com <batchParts>. O sufixo /$batch pertence à chamada que o adaptador faz ao serviço OData.

Dentro do lote, use batchQueryPart para uma consulta e batchChangeSet para agrupar gravações. O ChangeSet é a unidade atômica. Se duas gravações fazem parte do mesmo ChangeSet, ambas precisam dar certo para que o serviço aplique o grupo inteiro. ChangeSets separados têm resultados independentes. A especificação OData V2 também permite que o serviço processe as operações dentro de um ChangeSet em qualquer ordem. Especificação do $batch no OData V2

2. Prepare o ambiente de teste

Você precisa de um tenant Cloud Integration com acesso ao Design e ao Monitor, de um cliente HTTP como o Postman e de um serviço OData V2 gravável com suporte a $batch.

No laboratório, usei o serviço de demonstração OData V2 gravável do OData.org. A lista oficial também oferece o Northwind, que é um serviço separado, de leitura. Abra o endereço abaixo e copie a URL da sessão após o redirecionamento. Serviços de referência do OData.org

https://services.odata.org/V2/(S(readwrite))/OData/OData.svc/

Guarde a raiz da sessão como ODataBase no Postman. Use a mesma sessão no receiver do iFlow e nas consultas de conferência. O GET abaixo lista os produtos antes da primeira gravação.

GET {{ODataBase}}/Products?$select=ID,Name,Price&$format=json

Declare ODataBase sem a barra final. Se a sessão expirar ou voltar aos dados iniciais, gere outra, atualize o receiver e o Postman e consulte os IDs de novo. Os exemplos usam os IDs do meu laboratório. Confira quais existem na sua sessão e escolha um ID livre para criar um produto.

3. Monte o iFlow

  1. No Design, crie um pacote e adicione um artefato Integration Flow.
  2. Ligue o Sender ao evento Start com um adaptador HTTPS.
  3. Insira Request Reply entre Start e End. Se o editor deixar a linha direta entre os dois eventos, substitua-a pelas duas conexões que passam pelo Request Reply.
  4. Ligue o Request Reply ao Receiver com um adaptador OData V2.
  5. Aplique as configurações abaixo, salve e faça o Deploy. Em Monitor → Manage Integration Content → Endpoints, copie a URL implantada.
Onde Campo Valor do laboratório
HTTPS Sender · Connection Address /northwind_produtos_merge_batch
HTTPS Sender · Connection Authorization User Role, com ESBMessaging.send
HTTPS Sender · Connection CSRF Protected Desmarcado neste iFlow de laboratório
OData V2 Receiver · Connection Address Raiz do serviço OData V2, com a identificação da sua sessão
OData V2 Receiver · Connection Proxy Type / Authentication Internet / None, para o serviço público deste exercício
OData V2 Receiver · Connection CSRF Protected Desmarcado para o serviço de demonstração
OData V2 Receiver · Processing Operation Details / Resource Path Merge (MERGE) / Products, conforme o fluxo do laboratório
OData V2 Receiver · Processing Enable Batch Processing / Content Type Marcado / JSON

Com Enable Batch Processing ativo, as operações de cada parte vêm no XML. Por isso o fluxo configurado com Merge (MERGE) também executou consultas, POST e DELETE no lote misto. O Content Type do receiver define a conversão para o serviço de destino. O Postman continua enviando XML ao iFlow. Documentação do adaptador OData V2 Receiver

4. Envie o primeiro lote pelo Postman

Na sua subconta BTP, use uma instância SAP Process Integration Runtime, plano integration-flow, com a função ESBMessaging.send e uma service key do tipo ClientId/Secret. No Postman, guarde as credenciais como valores locais e use a URL do endpoint copiada do Monitor.

Campo no Postman Configuração
Método e URL POST para {{CPIEndpoint}}, a URL completa do iFlow
Authorization Basic Auth no laboratório, com clientid como usuário e clientsecret como senha
Headers Content-Type: application/xml
Body raw → XML, com o corpo abaixo

Para uso produtivo, a SAP recomenda opções como OAuth 2.0 Client Credentials ou certificado de cliente. Autenticação de entrada no Cloud Integration

Comece alterando apenas o preço de dois produtos. Aqui, as duas alterações pertencem ao mesmo ChangeSet. Use os IDs 0 e 1 se estiverem presentes na sua sessão.

<batchParts>
  <batchChangeSet>
    <batchChangeSetPart>
      <method>MERGE</method>
      <uri>Products(0)</uri>
      <Products>
        <Product>
          <ID>0</ID>
          <Price>3.5</Price>
        </Product>
      </Products>
    </batchChangeSetPart>
    <batchChangeSetPart>
      <method>MERGE</method>
      <uri>Products(1)</uri>
      <Products>
        <Product>
          <ID>1</ID>
          <Price>2.2</Price>
        </Product>
      </Products>
    </batchChangeSetPart>
  </batchChangeSet>
</batchParts>

No corpo da resposta, procure os statusCode das partes. Neste exercício, o resultado esperado é 204 No Content para cada MERGE. Depois, consulte os produtos diretamente para verificar os preços gravados.

GET {{ODataBase}}/Products(0)?$format=json
GET {{ODataBase}}/Products(1)?$format=json

5. Monte um lote com consulta, criação, alteração e exclusão

No exemplo a seguir, a consulta inicial lê o produto 5. Depois, o lote exclui o produto 6, cria o 9 e altera o preço do 4. A última consulta lê o produto que acabou de ser criado. Antes de enviar, confira se 4, 5 e 6 existem e se 9 está livre. Se trocar algum ID, ajuste também a URI correspondente e o ID no corpo da entidade, quando houver.

Estrutura do lote misto. Duas consultas ficam fora dos três ChangeSets de escrita. Cada ChangeSet executa uma gravação independente.

<?xml version="1.0" encoding="UTF-8"?>
<batchParts>
  <batchQueryPart>
    <method>GET</method>
    <uri>Products(5)</uri>
  </batchQueryPart>
  <batchChangeSet>
    <batchChangeSetPart>
      <method>DELETE</method>
      <uri>Products(6)</uri>
    </batchChangeSetPart>
  </batchChangeSet>
  <batchChangeSet>
    <batchChangeSetPart>
      <method>POST</method>
      <uri>Products</uri>
      <Products>
        <Product>
          <Description>8K LED Monitor</Description>
          <Price>800</Price>
          <Rating>5</Rating>
          <DiscontinuedDate/>
          <ID>9</ID>
          <ReleaseDate>2026-02-01T00:00:00.000</ReleaseDate>
          <Name>Monitor</Name>
        </Product>
      </Products>
    </batchChangeSetPart>
  </batchChangeSet>
  <batchChangeSet>
    <batchChangeSetPart>
      <method>MERGE</method>
      <uri>Products(4)</uri>
      <Products>
        <Product>
          <ID>4</ID>
          <Price>999</Price>
        </Product>
      </Products>
    </batchChangeSetPart>
  </batchChangeSet>
  <batchQueryPart>
    <method>GET</method>
    <uri>Products(9)</uri>
  </batchQueryPart>
</batchParts>

Na versão acima, usei consultas por chave para facilitar a reprodução. No laboratório original, o mesmo fluxo também executou consultas com $expand e $filter via customQueryInBatch=true, que já estava configurado no adaptador. Para incluir um & em uma URI dentro do XML, use &amp; ou uma seção CDATA como <![CDATA[Products?$expand=Category&$filter=ID eq 5]]>.

Confira cada operação

O status HTTP que aparece no topo do Postman descreve a chamada ao iFlow. Para saber se cada operação do lote funcionou, leia o statusCode de cada parte no corpo da resposta.

Códigos esperados, de cima para baixo. GET 200, DELETE 204, POST 201, MERGE 204 e GET 200.

Operação Status esperado Como conferir
GET produto 5 200 OK A parte de consulta traz o produto.
DELETE produto 6 204 No Content O produto deixa de aparecer na listagem.
POST produto 9 201 Created O produto aparece com o nome Monitor e preço 800.
MERGE produto 4 204 No Content O preço passa para 999.
GET produto 9 200 OK A parte de consulta traz o produto criado no lote.

No teste registrado, as consultas retornaram 200, o DELETE e o MERGE retornaram 204 e o POST retornou 201. A listagem final confirmou as três gravações. Se reenviar o mesmo lote, o produto excluído já terá sumido e o ID criado estará ocupado. Use uma sessão limpa ou escolha outros IDs.

6. Quando o preço grava e o nome fica em branco

No meu teste com o receiver em Atom, Price foi gravado, mas Name ficou nulo no POST. O $metadata desse serviço explica a diferença de representação. Em Atom, Name é mapeado para o título da entrada (SyndicationTitle) e Description para o resumo (SyndicationSummary), ambos com FC_KeepInContent="false".

Em OData V2 Receiver → Processing, alterei Content Type para JSON e fiz o Deploy novamente. Mantive o mesmo XML no Postman. No reteste, o produto 9 passou a aparecer como Monitor. Esse resultado confirmou a gravação de Name no POST. Naquele reteste, o MERGE alterou apenas Price, e a gravação de Description ficou sem confirmação.

Captura do laboratório SAP Cloud Integration com a aba Processing do receiver OData aberta e Content Type definido como JSON.

7. Diagnostique as falhas mais comuns

Sintoma Onde conferir
CannotResolveClassException: Products Confirme se a raiz do XML é <batchParts>. O nó Products fica dentro da operação de escrita.
Entity Set body not found in the edmx Dentro de batchChangeSetPart, use <Products><Product>…</Product></Products> para o corpo de POST ou MERGE. Para DELETE, envie método e URI.
404 em uma parte do lote Confira o ID e verifique se o iFlow e a consulta direta apontam para a mesma sessão do serviço de teste.
A chamada chegou ao iFlow, mas uma gravação falhou Leia o código interno da operação, confira o agrupamento dos ChangeSets e consulte o serviço para ver quais dados ficaram gravados.

Para investigar no CPI, abra Monitor → Message Processing e consulte Error Details e Logs. Se precisar enxergar o conteúdo de cada etapa, ative Trace temporariamente em Manage Integration Content → Log Configuration, reenvie a chamada e abra a nova execução. Faça isso com dados de teste.

Antes de encerrar o teste, confirme que o receiver está configurado para Batch Processing, que cada operação tem um status no corpo da resposta e que a consulta direta apresenta o resultado esperado na mesma sessão.

Referências

domingo, 29 de novembro de 2026

Ajuda de pesquisa no ABAP: MATCHCODE OBJECT e exit de função (SE11 e SE37)

Anotei aqui duas formas de ligar uma ajuda de pesquisa a um campo de tela. A simples usa MATCHCODE OBJECT direto no SELECT-OPTIONS. A outra cria uma ajuda de pesquisa própria na SE11 e uma exit de função na SE37 que monta a lista de valores.

Opção 1: MATCHCODE OBJECT no select-options

Para colocar uma ajuda de pesquisa (matchcode) em um SELECT-OPTIONS de uma tela 1000, basta incluir MATCHCODE OBJECT logo na frente da declaração, como no exemplo abaixo.

PARAMETERS: p_arq   LIKE rlgrap-filename OBLIGATORY,
            p_bukrs TYPE bsad_bck-bukrs OBLIGATORY DEFAULT '1000'.

SELECT-OPTIONS:
  s_hbkid FOR bsad_bck-hbkid OBLIGATORY NO-EXTENSION MATCHCODE OBJECT zshlp_hbkid,
  s_kunnr FOR bsad_bck-kunnr OBLIGATORY,
  s_augdt FOR bsad_bck-augdt OBLIGATORY,
  s_blart FOR bsad_bck-blart OBLIGATORY DEFAULT 'DZ' MATCHCODE OBJECT f4_blart,
  s_augbl FOR bsad_bck-augbl OBLIGATORY
          DEFAULT '1400000000' TO '1499999999' MATCHCODE OBJECT fmkk_f4_augbl.

O nome depois de MATCHCODE OBJECT pode ser uma ajuda de pesquisa standard (como f4_blart e fmkk_f4_augbl) ou uma criada por você (como zshlp_hbkid).

Exemplo: parâmetro de impressora

O mesmo recurso vale para um PARAMETERS. Para pedir a impressora na tela de seleção, há duas formas: só com o tipo do campo, ou com o tipo rspopname e o matchcode H_TSP03.

PARAMETERS: p_imp TYPE ssfpp-tddest.

" ou

PARAMETERS: p_imp TYPE rspopname MATCHCODE OBJECT h_tsp03.

Opção 2: ajuda de pesquisa própria com exit

Criando a ajuda de pesquisa

Na SE11, a ajuda de pesquisa elementar foi definida assim:

Definição da ajuda de pesquisa na SE11

Na tela, o método de seleção é ZTFI0055_1 e o tipo de diálogo é D (exibição de valores imediata). O campo de exit aponta para ZF4_SHLP_ID_SOLICITACAO, a função criada no passo seguinte. O parâmetro é ID_SOLICITACAO, marcado como IMP e EXP, com o elemento de dados ZE_ID_SOLICITACAO.

Exit para a ajuda de pesquisa

Na SE37, faça uma cópia da função F4IF_SHLP_EXIT_EXAMPLE para uma função Z.

SE37 com a função F4IF_SHLP_EXIT_EXAMPLE

Na cópia, informei o nome da nova função e o grupo de funções:

Copiar módulo funcional

O grupo de funções criado foi ZGF_EXIT_SHLP_PROC_TRANSF.

Função ZF4_SHLP_ID_SOLICITACAO

A função copiada só trata os steps SELONE, SELECT e DISP. O código de preenchimento da lista fica no step SELECT, que chama um PERFORM step_select. Os tipos globais ficam no topo do include do grupo de funções.

TYPES: BEGIN OF yt_ztfi0055,
         object  TYPE ze_object,
         nrlevel TYPE ze_nrlevel,
       END OF yt_ztfi0055,
       ytt_ztfi0055 TYPE STANDARD TABLE OF yt_ztfi0055.


FUNCTION zf4_shlp_id_solicitacao.
*"----------------------------------------------------------------------
*"*"Interface local:
*"  TABLES
*"      SHLP_TAB TYPE  SHLP_DESCT
*"      RECORD_TAB STRUCTURE  SEAHLPRES
*"  CHANGING
*"     VALUE(SHLP) TYPE  SHLP_DESCR
*"     VALUE(CALLCONTROL) LIKE  DDSHF4CTRL STRUCTURE  DDSHF4CTRL
*"----------------------------------------------------------------------

* EXIT immediately, if you do not want to handle this step
  IF callcontrol-step <> 'SELONE' AND
     callcontrol-step <> 'SELECT' AND
     " AND SO ON
     callcontrol-step <> 'DISP'.
    EXIT.
  ENDIF.

*"----------------------------------------------------------------------
* STEP SELONE  (Select one of the elementary searchhelps)
*"----------------------------------------------------------------------
* This step is only called for collective searchhelps. It may be used
* to reduce the amount of elementary searchhelps given in SHLP_TAB.
* The compound searchhelp is given in SHLP.
* If you do not change CALLCONTROL-STEP, the next step is the
* dialog, to select one of the elementary searchhelps.
* If you want to skip this dialog, you have to return the selected
* elementary searchhelp in SHLP and to change CALLCONTROL-STEP to
* either to 'PRESEL' or to 'SELECT'.
  IF callcontrol-step = 'SELONE'.
*   PERFORM SELONE .........
    EXIT.
  ENDIF.

*"----------------------------------------------------------------------
* STEP PRESEL  (Enter selection conditions)
*"----------------------------------------------------------------------
* This step allows you, to influence the selection conditions either
* before they are displayed or in order to skip the dialog completely.
* If you want to skip the dialog, you should change CALLCONTROL-STEP
* to 'SELECT'.
* Normaly only SHLP-SELOPT should be changed in this step.
  IF callcontrol-step = 'PRESEL'.
*   PERFORM PRESEL ..........
    EXIT.
  ENDIF.

*"----------------------------------------------------------------------
* STEP SELECT    (Select values)
*"----------------------------------------------------------------------
* This step may be used to overtake the data selection completely.
* To skip the standard seletion, you should return 'DISP' as following
* step in CALLCONTROL-STEP.
* Normally RECORD_TAB should be filled after this step.
* Standard function module F4UT_RESULTS_MAP may be very helpfull in this
* step.
  IF callcontrol-step = 'SELECT'.
    DATA: t_ztfi0055 TYPE ytt_ztfi0055,
          l_subrc    TYPE sy-subrc.
    PERFORM step_select TABLES record_tab shlp_tab
                        CHANGING shlp callcontrol l_subrc
                                 t_ztfi0055.
*   IF RC = 0.
    IF l_subrc = 0.
      callcontrol-step = 'DISP'.
    ELSE.
      callcontrol-step = 'EXIT'.
    ENDIF.
    EXIT. "Don't process STEP DISP additionally in this call.
  ENDIF.

*"----------------------------------------------------------------------
* STEP DISP     (Display values)
*"----------------------------------------------------------------------
* This step is called, before the selected data is displayed.
* You can e.g. modify or reduce the data in RECORD_TAB
* according to the users authority.
* If you want to get the standard display dialog afterwards, you
* should not change CALLCONTROL-STEP.
* If you want to overtake the dialog on you own, you must return
* the following values in CALLCONTROL-STEP:
* - "RETURN" if one line was selected. The selected line must be
*   the only record left in RECORD_TAB. The corresponding fields of
*   this line are entered into the screen.
* - "EXIT" if the values request should be aborted
* - "PRESEL" if you want to return to the selection dialog
* Standard function modules F4UT_PARAMETER_VALUE_GET and
* F4UT_PARAMETER_RESULTS_PUT may be very helpfull in this step.
  IF callcontrol-step = 'DISP'.
*   PERFORM AUTHORITY_CHECK TABLES RECORD_TAB SHLP_TAB
*                           CHANGING SHLP CALLCONTROL.
    EXIT.
  ENDIF.
ENDFUNCTION.

FORM step_select

O PERFORM acima aponta para este form, criado no include LZGF_EXIT_SHLP_PROC_TRANSFF01. Ele lê os registros com status 2 da tabela ZTFI0055_1, monta o valor concatenando nrlevel e object e devolve cada valor na ajuda de pesquisa com F4UT_PARAMETER_RESULTS_PUT.

*----------------------------------------------------------------------*
***INCLUDE LZGF_EXIT_SHLP_PROC_TRANSFF01.
*----------------------------------------------------------------------*
*&---------------------------------------------------------------------*
*&      Form  STEP_SELECT
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
*      -->P_RECORD_TAB  text
*      -->P_SHLP_TAB    text
*      <--P_SHLP        text
*      <--P_CALLCONTROL text
*      <--P_RC          text
*----------------------------------------------------------------------*
FORM step_select TABLES p_record_tab TYPE dmc_seahlpres_table
                        p_shlp_tab   TYPE shlp_desct
                 CHANGING p_shlp        TYPE shlp_descr
                          p_callcontrol TYPE ddshf4ctrl
                          p_subrc       TYPE sy-subrc
                          p_ztfi0055    TYPE ytt_ztfi0055.

  TYPES: BEGIN OF y_teste,
           id_solicitacao TYPE ze_id_solicitacao,
         END OF y_teste.

  DATA: lt_teste TYPE STANDARD TABLE OF y_teste,
        ls_teste LIKE LINE OF lt_teste,
        l_fname  TYPE dfies-lfieldname.

  SELECT object
         nrlevel
    FROM ztfi0055_1
    INTO TABLE p_ztfi0055
    WHERE status = '2'.

  IF sy-subrc = 0.
    LOOP AT p_ztfi0055 INTO DATA(ls_0055).
      ls_teste-id_solicitacao = |{ ls_0055-nrlevel }{ ls_0055-object }|.
      APPEND ls_teste TO lt_teste.
    ENDLOOP.
  ENDIF.

  IF sy-subrc = 0.
    LOOP AT p_shlp_tab.
      LOOP AT p_shlp_tab-fielddescr INTO DATA(ls_fields).
        l_fname = ls_fields-fieldname.
        CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
          EXPORTING
            parameter         = ls_fields-fieldname
            fieldname         = l_fname
          TABLES
            shlp_tab          = p_shlp_tab
            record_tab        = p_record_tab
            source_tab        = lt_teste
          CHANGING
            shlp              = p_shlp
            callcontrol       = p_callcontrol
          EXCEPTIONS
            parameter_unknown = 1
            OTHERS            = 2.

        p_subrc = sy-subrc.

      ENDLOOP.
    ENDLOOP.
  ENDIF.
ENDFORM.

sábado, 28 de novembro de 2020

Adicionar novo campo customizado na aba de vendas da transação VA01/VA02 - Ordem de venda

Aqui irei explicar como adicionar um novo campo na aba de vendas das transações VA01 e VA02 - Criação e modificação da ordem de vendas. Consegui essa dica lendo o link abaixo: https://ilakkiasabap.wordpress.com/2019/02/01/add-a-new-field-in-va01-header/ Um resumo do conteudo do link citado: ADD A NEW FIELD IN VA01 HEADER Hi, I had a requirement to add a new field in the VA01 header. In SD, an User Exit can be used to provide any enhancement. I have added a new field as below steps. Below are the screen numbers in the program SAPMV45A and their following uses. 8309 in the “Header data – Additional Data B” tab. 8310 in the “Overview – Sales” tab. Dynpro 8310 is displayed as a subscreen, between the standard header fields and item’s table control on that tab (dynpro 4440). 8459 in the “Item data – Additional Data B” tab. 8460 in the bottom of “Overview – Item detail” tab. No programa SAPMV45A existe uma tela de número 8310 exatamente para esse propósito. Devemos procurar essa tela no programa SAPMV45A, clicar em layout para desenhar os novos campos que serão apresentados
Voce poderá realizar sua lógica tanto no PAI, quanto no PBO. Não será necessário uma chave sap para isso, usuario com o perfil de abap consegue criar.
Ativa tudo e veja o resultado: O campo é exibido conforme imagem:

quinta-feira, 25 de novembro de 2010

BAPI_SHIPMENT_CHANGE

Estive com alguns problemas em usar a BAPI  BAPI_SHIPMENT_CHANGE.
Ela bloqueava todos registros que só eram desbloqueados quando a janela do programa que chamava a bapi era fechado.

Mesmo problema relatado neste link:

Primeiro fazia a chamada da BAPI, em seguida chamava a bapi BAPI_TRANSACTION_COMMIT.

Para resolver o problema, fiz a chamada da bapi da seguinte forma:


 CALL FUNCTION 'BAPI_SHIPMENT_CHANGE'  STARTING NEW TASK sy-uzeit
      EXPORTING
        headerdata       = lwa_headerdata
        headerdataaction = lwa_headerdataaction
      TABLES
        return           = lt_return.

    READ TABLE lt_return INTO lwa_return WITH KEY type = 'E'.
    IF sy-subrc = 0 AND
      ( NOT okcode = 'DELE' OR
         ( okcode = 'DELE' AND NOT v_ck_prg IS INITIAL ) ).
      MESSAGE w208(00) WITH lwa_return-message.
*      ENDIF.
    ELSE.
      WAIT UP TO 2 SECONDS.
      CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'
        EXPORTING
          wait = 'X'.

Fica aqui a dica

segunda-feira, 4 de outubro de 2010

BAPI BAPI_SALESORDER_CHANGE

Segue um exemplo de como utilizar a bapi BAPI_SALESORDER_CHANGE para retirar quantidade de um item de uma ordem disponivel na VA02.
Como é um trecho de um programa apenas, podem observar que existe lixo nesta copia de código abaixo, podendo descartar algumas coisas...


types:
begin of ty_aufk,
aufnr type aufk-aufnr,
kdauf type aufk-kdauf,
end of ty_aufk,
begin of ty_aufk_aux,
aufnr type zqme_est_placa-aufnr,
charg type zqme_est_placa-charg,
erfmg type zqme_est_placa-erfmg,
kdauf type aufk-kdauf,
end of ty_aufk_aux,

begin of ty_mska,
charg type mska-charg ,
vbeln type mska-vbeln ,
posnr type mska-posnr ,
kalab type mska-kalab ,
end of ty_mska,

begin of ty_schedule_line,
vbeln type vbep-vbeln, "Sales Document
posnr type vbep-posnr, "Sales Document Item
etenr type vbep-etenr, "Delivery Schedule Line Number
ettyp type vbep-ettyp, "Schedule line category
wmeng type vbep-wmeng,
vrkme type vbep-vrkme,
edatu type vbep-edatu,
end of ty_schedule_line.


data: t_aufk type standard table of ty_aufk,
t_aufk_aux type standard table of ty_aufk_aux,
t_mska type standard table of ty_mska,
t_estpl_aux1 type standard table of zqme_est_placa,
t_processcome type standard table of zppt_processcome,
t_schedule_line type standard table of ty_schedule_line,
wa_processcome like line of t_processcome,
wa_aufk like line of t_aufk,
wa_aufk_aux like line of t_aufk_aux,
wa_mska like line of t_mska,
wa_estlp_aux1 like line of t_estpl_aux1,
wa_schedule_line like line of t_schedule_line.

*-BAPI Sales Order change
data: t_order_item_in_bapi type standard table of bapisditm,
t_order_item_inx_bapi type standard table of bapisditmx,
t_schedule_lines_bapi type standard table of bapischdl,
t_schedule_linesx_bapi type standard table of bapischdlx,
t_return_so_change type standard table of bapiret2,
t_schedule_line_loc type standard table of ty_schedule_line,

*-BAPI_SALESORDER_GETSTATUS
l_return like bapireturn,
lt_statusinfo type standard table of bapisdstat,
lwa_statusinfo like line of lt_statusinfo,


wa_order_item_in_bapi like line of t_order_item_in_bapi,
wa_order_item_inx_bapi like line of t_order_item_inx_bapi,
wa_schedule_lines_bapi like line of t_schedule_lines_bapi,
wa_schedule_linesx_bapi like line of t_schedule_linesx_bapi,
wa_return_so_change like line of t_return_so_change,
wa_return_commit type bapiret2,


l_salesdocument type bapivbeln-vbeln,
wa_order_header_inx type bapisdh1x,
l_posnr type mska-posnr,
l_error_bapi type i,
l_message(80) type c,
l_erfmg type erfmg.


l_posnr = 10.

loop at t_estpl_aux1 into wa_estlp_aux1.
read table t_aufk into wa_aufk with key aufnr = wa_estlp_aux1-aufnr.
if sy-subrc = 0.
l_salesdocument = wa_aufk-kdauf.
wa_order_header_inx-updateflag = 'U'.
call function 'BAPI_SALESORDER_GETSTATUS'
exporting
salesdocument = l_salesdocument
importing
return = l_return
tables
statusinfo = lt_statusinfo.

if not lt_statusinfo[] is initial.

select vbeln posnr etenr ettyp wmeng vrkme edatu "#CR
into table t_schedule_line
from vbep
for all entries in lt_statusinfo
where vbeln = l_salesdocument
and posnr = lt_statusinfo-itm_number.
if sy-subrc = 0.

sort t_schedule_line by edatu descending posnr ascending.

t_schedule_line_loc[] = t_schedule_line[].

read table t_aufk_aux into wa_aufk_aux with key kdauf = wa_aufk-kdauf
aufnr = wa_estlp_aux1-aufnr
charg = wa_estlp_aux1-charg.
if sy-subrc = 0.
read table t_mska into wa_mska with key charg = wa_aufk_aux-charg
vbeln = wa_aufk_aux-kdauf.
if sy-subrc = 0.
wa_order_item_in_bapi-itm_number = wa_mska-posnr.
wa_order_item_inx_bapi-itm_number = wa_mska-posnr.
wa_order_item_inx_bapi-updateflag = 'U'.
read table lt_statusinfo into lwa_statusinfo with key itm_number = wa_order_item_in_bapi-itm_number.
if sy-subrc = 0.
wa_order_item_in_bapi-target_qty = lwa_statusinfo-req_qty - wa_estlp_aux1-erfmg.
wa_order_item_inx_bapi-target_qty = 'X'.
append: wa_order_item_in_bapi to t_order_item_in_bapi,
wa_order_item_inx_bapi to t_order_item_inx_bapi.
endif.
t_schedule_line_loc[] = t_schedule_line[].

delete t_schedule_line_loc where posnr ne wa_mska-posnr.
sort t_schedule_line_loc by edatu descending posnr ascending.
loop at t_schedule_line_loc into wa_schedule_line.
wa_schedule_lines_bapi-itm_number = wa_schedule_line-posnr.
wa_schedule_linesx_bapi-itm_number = wa_schedule_line-posnr.
wa_schedule_lines_bapi-sched_line = wa_schedule_line-etenr.
wa_schedule_linesx_bapi-sched_line = wa_schedule_line-etenr.
wa_schedule_lines_bapi-sched_type = wa_schedule_line-ettyp.
wa_schedule_lines_bapi-req_date = wa_schedule_line-edatu.
wa_schedule_linesx_bapi-req_date = 'X'.
wa_schedule_linesx_bapi-sched_type = 'X'.
if sy-tabix = '1'.
l_erfmg = wa_estlp_aux1-erfmg.
endif.
if wa_schedule_line-wmeng > l_erfmg.
wa_schedule_lines_bapi-req_qty = wa_schedule_line-wmeng - l_erfmg.
wa_schedule_linesx_bapi-req_qty = 'X'.
wa_schedule_linesx_bapi-updateflag = 'U'.
append wa_schedule_lines_bapi to t_schedule_lines_bapi[].
append wa_schedule_linesx_bapi to t_schedule_linesx_bapi[].
else.
l_erfmg = l_erfmg - wa_schedule_line-wmeng.
wa_schedule_lines_bapi-req_qty = 0.
wa_schedule_linesx_bapi-req_qty = 'X'.
wa_schedule_linesx_bapi-updateflag = 'D'.
append wa_schedule_lines_bapi to t_schedule_lines_bapi[].
append wa_schedule_linesx_bapi to t_schedule_linesx_bapi[].
endif.
endloop.

clear: wa_order_item_in_bapi, wa_order_item_inx_bapi.
read table lt_statusinfo into lwa_statusinfo with key itm_number = l_posnr.
if sy-subrc = 0.
wa_order_item_in_bapi-itm_number = l_posnr.
wa_order_item_inx_bapi-itm_number = l_posnr.
wa_order_item_inx_bapi-updateflag = 'U'.
wa_order_item_in_bapi-target_qty = lwa_statusinfo-req_qty + wa_estlp_aux1-erfmg.
wa_order_item_inx_bapi-target_qty = 'X'.
append: wa_order_item_in_bapi to t_order_item_in_bapi,
wa_order_item_inx_bapi to t_order_item_inx_bapi.
endif.

t_schedule_line_loc[] = t_schedule_line[].

delete t_schedule_line_loc where posnr ne l_posnr.
sort t_schedule_line_loc by edatu descending posnr ascending.
read table t_schedule_line_loc into wa_schedule_line index 1.
if sy-subrc = 0.
wa_schedule_lines_bapi-itm_number = wa_schedule_line-posnr.
wa_schedule_linesx_bapi-itm_number = wa_schedule_line-posnr.
wa_schedule_lines_bapi-sched_line = wa_schedule_line-etenr.
wa_schedule_linesx_bapi-sched_line = wa_schedule_line-etenr.
wa_schedule_lines_bapi-sched_type = wa_schedule_line-ettyp.
wa_schedule_lines_bapi-req_date = wa_schedule_line-edatu.
wa_schedule_linesx_bapi-req_date = 'X'.
wa_schedule_linesx_bapi-sched_type = 'X'.

wa_schedule_lines_bapi-req_qty = wa_schedule_line-wmeng + wa_estlp_aux1-erfmg.
wa_schedule_linesx_bapi-req_qty = 'X'.
wa_schedule_linesx_bapi-updateflag = 'U'.
append wa_schedule_lines_bapi to t_schedule_lines_bapi[].
append wa_schedule_linesx_bapi to t_schedule_linesx_bapi[].
endif.
endif.
endif.
call function 'BAPI_SALESORDER_CHANGE'
exporting
salesdocument = l_salesdocument
order_header_inx = wa_order_header_inx
tables
return = t_return_so_change
order_item_in = t_order_item_in_bapi
order_item_inx = t_order_item_inx_bapi
schedule_lines = t_schedule_lines_bapi
schedule_linesx = t_schedule_linesx_bapi.

read table t_return_so_change into wa_return_so_change with key type = 'E'.
if sy-subrc = 0.
l_message = wa_return_so_change-message.

m_insere_log: 'Documento não foi modificado ' .
m_insere_log: l_salesdocument .
m_insere_log: l_message.
m_insere_log: '------------------------------------------' .

else.
call function 'BAPI_TRANSACTION_COMMIT'
exporting
wait = 'X'
importing
return = wa_return_commit.
endif.


endif.
endif.
endif.

endloop.



Inserindo botão em tela 1000

Para inserirmos um botão no topo de uma tela 1000 existe a seguinte linha de comando:

selection-screen function key 1.

Para utiliza-la basta utilizar a colinha abaixo:

report zinsertrequest.

type-pools: ctslg , icon, slis.
include: <icon>.

tables: e070, sscrfields.
include: rsvcmacr.

************************************************************************
* Definição de estruturas: TY_... *
************************************************************************
types:
begin of ty_requests,
trkorr like e070-trkorr, "REQUEST
ddtext type dd07t-ddtext, "TIPO REQUEST
ambiente(100), "LIKE tstrfcofil-tarsystem, "Ambiente
as4user like e070-as4user,"USUARIO
autor type sy-uname,
as4date like e070-as4date,"DATA
as4time like e070-as4time,"HORA
as4text like e07t-as4text,"DESCRICAO
end of ty_requests,
begin of ty_dd07t,
domvalue_l type dd07t-domvalue_l,
ddtext type dd07t-ddtext,
end of ty_dd07t,
begin of ty_ctslg_cofile,
exists type c,
imported type c,
del_lines_only type c,
systems type ctslg_systems,
merges type ctslg_mergelines,
rc type i,
end of ty_ctslg_cofile.

data: d_butt1(4).

************************************************************************
* Variáveis de Referência ( RV_...) *
************************************************************************
data: rv_structure type ref to data,
rv_table type ref to data,
rv_struc_desc type ref to cl_abap_structdescr,

************************************************************************
* Tabela Interna ( T_...) *
************************************************************************
t_lvc_fieldcatalogue type lvc_t_fcat,
t_fieldcatalogue type slis_t_fieldcat_alv,
t_es_cofile type ty_ctslg_cofile,
t_e070 type standard table of e070,
t_e07t type standard table of e07t,
t_amb type standard table of ctslg_system,
t_requests type standard table of ty_requests,
t_dd07t type standard table of ty_dd07t,
t_tp_obj type standard table of ko100,

************************************************************************
* Work Area ( wa_...) *
************************************************************************
wa_layout type slis_layout_alv,
wa_fieldcatalogue type slis_fieldcat_alv,
wa_lvc_fieldcatalogue type lvc_s_fcat,
wa_e070 like line of t_e070,
wa_e07t like line of t_e07t,
wa_amb like line of t_amb,
wa_requests like line of t_requests,
wa_dd07t like line of t_dd07t,
wa_tp_obj like line of t_tp_obj.

************************************************************************
* Field Symbols (< fs_...> ) *
************************************************************************
*field symbols declaration
field-symbols :
<fs_it_table> type standard table,
<fs_dyn_str> type any,
<fs_str_comp> type abap_compdescr.

************************************************************************
* Constantes ( c_...) *
************************************************************************
data: c_tab type dd02l-tabname value 'ZTUPDREQ'.

************************************************************************
* Variáveis Globais (v_...) *
************************************************************************
data : v_t1 type dd02t-ddtext,
v_t2(50) type c,
v_t3(50) type c,
v_table type dd02l-tabname.


************************************************************************
* Tela de seleção
************************************************************************
selection-screen begin of block b1 with frame title text-001.

select-options: s_req for e070-trkorr.
selection-screen function key 1.

selection-screen end of block b1.

************************************************************************
initialization.
************************************************************************
move 'Exibir Registros' to sscrfields-functxt_01.
move 'Exibir Registros' to sscrfields-functxt_02.
d_butt1 = 'NO'.

v_table = c_tab.
select single ddtext
from dd02t
into v_t1
where tabname = c_tab
and ddlanguage = sy-langu.

************************************************************************
at selection-screen.
************************************************************************
if sy-ucomm = 'FC01'.
d_butt1 = 'YES'.
sscrfields-ucomm = 'ONLI'.
endif.

************************************************************************
start-of-selection.
************************************************************************
if d_butt1 = 'NO'.
if not s_req[] is initial.
perform seleciona_dados.
if not t_requests[] is initial.
perform insere_reg_tab.
endif.
endif.
elseif d_butt1 = 'YES'.
perform exibe_alv.
d_butt1 = 'NO'.
endif.

sexta-feira, 11 de junho de 2010

Inclusão de COR em determinada Celula do ALV

Este é um exemplo de código onde conseguimos definir cor em uma única celula de um ALV por função.
A dica é basicamente incluir na tabela de saida o elemento de dados tabcolor type lvc_t_scol e colocar os valores neles referentes a cada linha...

*&---------------------------------------------------------------------*
*& Report Z_ALV_CELL_COLOR
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

report Z_ALV_CELL_COLOR.


*---------------------------------------------------------------------*
* Example of ALV with Cell color *
*---------------------------------------------------------------------*
* Author : Michel PIOUD *
*---------------------------------------------------------------------*
* Macro definition
define m_fieldcat.
add 1 to ls_fieldcat-col_pos.
ls_fieldcat-fieldname = &1.
ls_fieldcat-ref_tabname = &2.
append ls_fieldcat to lt_fieldcat.
end-of-definition.

type-pools: slis. " ALV Global types

selection-screen :
skip, begin of line,comment 5(27) v_1 for field p_max. "#EC NEEDED
parameters p_max(2) type n default '30' obligatory. "#EC *
selection-screen end of line.

types :
begin of ty_data,
vkorg type vbak-vkorg, " Sales organization
kunnr type vbak-kunnr, " Sold-to party
vbeln type vbak-vbeln, " Sales document
netwr type vbak-netwr, " Net Value of the Sales Order
end of ty_data,

* Data displayed
begin of ty_vbak,
vkorg type vbak-vkorg, " Sales organization
kunnr type vbak-kunnr, " Sold-to party
vbeln type vbak-vbeln, " Sales document
netwr type vbak-netwr, " Net Value of the Sales Order
tabcolor type lvc_t_scol, " Cell Color
end of ty_vbak.

data:
gt_data type table of ty_data,
* Data displayed
gt_vbak type table of ty_vbak.

*---------------------------------------------------------------------*
initialization.

v_1 = 'Maximum of records to read'. "#EC NOTEXT

*---------------------------------------------------------------------*
start-of-selection.
break abaptista.
perform f_read_data.

perform f_fill_color.

perform f_display_data.

*---------------------------------------------------------------------*
* Form f_read_data_vbak
*---------------------------------------------------------------------*
form f_read_data.

select * into corresponding fields of table gt_data
from vbak up to p_max rows.

endform. " F_READ_DATA
*--------------------------------------------------------------------*
* Form f_fill_color
*--------------------------------------------------------------------*
form f_fill_color.

data :
ls_data type ty_data,
ls_vbak type ty_vbak.

loop at gt_data into ls_data.

clear ls_vbak.
move-corresponding ls_data to ls_vbak.

perform f_modify_color using 'NETWR' changing ls_vbak.
perform f_modify_color using 'VBELN' changing ls_vbak.

* Fill gt_vbak
append ls_vbak to gt_vbak.

endloop.

endform. " F_FILL_COLOR
*---------------------------------------------------------------------*
* Form F_modify_color
*---------------------------------------------------------------------*
form f_modify_color using u_fieldname type lvc_fname
changing us_vbak type ty_vbak.

data :
l_rnd_value type integer2,
ls_tabcolor type lvc_s_scol.

* Random value
call function 'RANDOM_I2'
exporting
rnd_min = 0
rnd_max = 3
importing
rnd_value = l_rnd_value.

clear ls_tabcolor.
ls_tabcolor-fname = u_fieldname.

case l_rnd_value.
when 0.
ls_tabcolor-color-col = 1. " Blue.
ls_tabcolor-color-int = 0.
ls_tabcolor-color-inv = 0.
when 1.
ls_tabcolor-color-col = 3. " Yellow.
ls_tabcolor-color-int = 0.
ls_tabcolor-color-inv = 0.
when 2.
ls_tabcolor-color-col = 5. " Green.
ls_tabcolor-color-int = 0.
ls_tabcolor-color-inv = 0.
when 3.
ls_tabcolor-color-col = 6. " Red.
ls_tabcolor-color-int = 0.
ls_tabcolor-color-inv = 0.
endcase.

insert ls_tabcolor into table us_vbak-tabcolor.

endform. " F_MODIFY_COLOR
*---------------------------------------------------------------------*
* Form f_display_data
*---------------------------------------------------------------------*
form f_display_data.

data:
ls_layout type slis_layout_alv,
ls_fieldcat type slis_fieldcat_alv,
lt_fieldcat type slis_t_fieldcat_alv.

* Build the field catalog
m_fieldcat 'VKORG' 'VBAK'.
m_fieldcat 'KUNNR' 'VBAK'.
m_fieldcat 'VBELN' 'VBAK'.
m_fieldcat 'NETWR' 'VBAK'.

* Fill Layout
ls_layout-coltab_fieldname = 'TABCOLOR'.

* Display the list
call function 'REUSE_ALV_GRID_DISPLAY'
exporting
is_layout = ls_layout
it_fieldcat = lt_fieldcat
tables
t_outtab = gt_vbak.

endform. " F_DISPLAY_DATA
***************** END OF PROGRAM Z_ALV_CELL_COLOR *********************