cancel
Showing results for 
Search instead for 
Did you mean: 

Authorization error when using external service in value help in SAP CAP

01-01-2022 6:48 PM
Ahmedkhan29789 Participant
20598 views 32 comments Go to solution
0 Likes
SAP Managed Tags
Subscribe

In continuation of using external service in SAP CAP, which was resolved in this answer , I am trying to consume the external service data in the value help of a service created in SAP CAP only, And I am getting authorization error in console. when clicking on value help button in my application. Although all the authorization of external service has already been defined in my package.json and that's why its showing json data of external service on CDS WATCH, but when running a FIORI elements app made on the inetrnal entitySET "Promotions", Its not showing data in value help and saying in console "You need authorization to display this object."

My schema CDS looks like this

namespace com.sap.ibp;

using {managed} from '@sap/cds/common';
using {SapIbp as external} from '../srv/external/SapIbp.csn';
entity Promotions : managed {
    key PROMOTION_ID              : UUID
            @title : '{i18n>PROMOTION_ID}'
            @Core.Computed;
        PROMOTION_TYPE            : String
            @title : '{i18n>PROMOTION_TYPE}';
        PROMOTION_DATE            : Date
            @title : '{i18n>PROMOTION_DATE}';
        DURATION                  : String
            @title : '{i18n>DURATION}';
        PRODUCT_ID                : Association to many external.BTPPROMO
            @title : '{i18n>PRODUCT_ID}';
        CUSTOMER_ID               : Association to many external.BTPPROMO
            @title : '{i18n>CUSTOMER_ID}';
        PROMOTION_QTY             : Integer
            @title : '{i18n>PROMOTION_QTY}';
        PROMOTION_PRICE           : Double
            @title : '{i18n>PROMOTION_PRICE}';
        DISCOUNT_PERCENTAGE       : Double
            @title : '{i18n>DISCOUNT_PERCENTAGE}';
        SALES_RED_PREV_PRD        : Double
            @title : '{i18n>SALES_RED_PREV_PRD}';
        SALES_RED_PREV_PERCENTAGE : Double
            @title : '{i18n>SALES_RED_PREV_PERCENTAGE}';
        SALES_RED_FUTR_PRD        : Double
            @title : '{i18n>SALES_RED_FUTR_PRD}';
        SALES_RED_FUTR_PERCENTAGE : Double
            @title : '{i18n>SALES_RED_FUTR_PERCENTAGE}';
        PLANNER                   : String
            @title : '{i18n>PLANNER}';
        PLANNING_NOTE             : LargeString
            @title : '{i18n>PLANNING_NOTE}';
};

annotate Promotions with @(
    title : '{i18n>PRODUCT_ID}',
    UI.TextArrangement : #TextOnly,
    cds.odata.valuelist,
    Common.SemanticKey : [PRODUCT_ID],
    UI.Identification  : [{
        $Type : 'UI.DataField',
        Value : 'PRDID'

    }]
)
{
PRODUCT_ID         @(
        PRODUCT_ID                           : '{i18n>title}',
        Common.ValueListWithFixedValues : false,
        Common.ValueList                : {
            CollectionPath : 'BTPPROMO',
            Parameters     : [{
                $Type             : 'Common.ValueListParameterInOut',
                LocalDataProperty : 'PRODUCT_ID',
                ValueListProperty : 'PRDID'
            }]
        }
    );
CUSTOMER_ID         @(
        CUSTOMER_ID                           : '{i18n>title}',
        Common.ValueListWithFixedValues : false,
        Common.ValueList                : {
            CollectionPath : 'BTPPROMO',
            Parameters     : [{
                $Type             : 'Common.ValueListParameterInOut',
                LocalDataProperty : 'CUSTOMER_ID',
                ValueListProperty : 'CUSTID'
            }]
        }
    );    
}

The error I am getting when pressing value help for "PRODUCT_ID" is
user: sap-ibp-promotions $ cds watch
 
cds serve all --with-mocks --in-memory? 
watching: cds,csn,csv,ts,mjs,cjs,js,json,properties,edmx,xml,env,css,gif,html,jpg,png,svg... 
live reload enabled for browsers 
        _______________________
 
[cds] - Loading server from { file: './srv/server.js' }
#2.0#2022 01 01 17:19:02:161#+00:00#WARNING#/LoggingLibrary################PLAIN##Dynamic log level switching not available#
[HPM] Proxy created: /  -> http://localhost:4004
[HPM] Proxy rewrite rule created: "^/v2" ~> ""
[cds] - model loaded from 6 file(s):

  ./db/promotions-model.cds
  ./srv/catalog-service.cds
  ./app/services.cds
  ./srv/external/SapIbp.csn
  ./node_modules/@sap/cds/common.cds
  ./app/promotions/annotations.cds

[cds] - connect using bindings from: { registry: '~/.cds-services.json' }
[cds] - connect to db > sqlite { database: ':memory:' }
/> successfully deployed to sqlite in-memory db

[cds] - connect to SapIbp > odata { destination: 'SAP_IBP_EPAM' }
[cds] - serving PromotionService {
  at: '/sap/opu/odata/sap/API_IBP_PROMOTIONS',
  impl: './srv/catalog-service.js'
}

[cds] - server listening on { url: 'http://localhost:4004' }
[cds] - launched at 1/1/2022, 5:19:01 PM, in: 992.277ms
[cds] - [ terminate with ^C ]

[cds] - GET /appconfig/fioriSandboxConfig.json
[cds] - GET /sap/opu/odata/sap/ESH_SEARCH_SRV/ServerInfos?$expand=Services/Capabilities
[cds] - GET /sap/es/ina/GetServerInfo?_=1641057554816
[cds] - GET /promotions/webapp/Component-preload.js
[cds] - GET /promotions/webapp/Component-preload.js
[cds] - GET /promotions/webapp/i18n/i18n_en_GB.properties
[cds] - GET /promotions/webapp/i18n/i18n_en.properties
[cds] - GET /promotions/webapp/i18n/i18n_en_GB.properties
[cds] - GET /promotions/webapp/i18n/i18n_en.properties
[cds] - GET /promotions/webapp/i18n/i18n_en_GB.properties
[cds] - GET /promotions/webapp/i18n/i18n_en.properties
[cds] - GET /sap/opu/odata/sap/API_IBP_PROMOTIONS/$metadata?sap-language=6N
[cds] - HEAD /sap/opu/odata/sap/API_IBP_PROMOTIONS/
[cds] - GET /sap/bc/lrep/flex/data/com.epam.promotions.Component?sap-language=en-GB
[cds] - GET /sap/bc/lrep/flex/settings
[cds] - POST /sap/opu/odata/sap/API_IBP_PROMOTIONS/$batch
[cds] - > NEW Promotions 
[cds] - POST /sap/opu/odata/sap/API_IBP_PROMOTIONS/$batch
[cds] - > READ Promotions(PROMOTION_ID=8873f85e-fbaf-4ac9-b60f-4a0c22d9beff,IsActiveEntity=false) {
  '$select': 'CUSTOMER_ID_ID,DISCOUNT_PERCENTAGE,DURATION,HasActiveEntity,HasDraftEntity,IsActiveEntity,PLANNER,PLANNING_NOTE,PRODUCT_ID_ID,PROMOTION_DATE,PROMOTION_ID,PROMOTION_PRICE,PROMOTION_QTY,PROMOTION_TYPE,SALES_RED_FUTR_PERCENTAGE,SALES_RED_FUTR_PRD,SALES_RED_PREV_PERCENTAGE,SALES_RED_PREV_PRD',
  '$expand': 'DraftAdministrativeData($select=DraftIsCreatedByMe,DraftUUID,InProcessByUser),PRODUCT_ID($select=ID)'
}
[cds] - POST /sap/opu/odata/sap/API_IBP_PROMOTIONS/$batch
[cds] - > READ Promotions(PROMOTION_ID=8873f85e-fbaf-4ac9-b60f-4a0c22d9beff,IsActiveEntity=false) {
  '$select': 'CUSTOMER_ID_ID,DISCOUNT_PERCENTAGE,DURATION,HasActiveEntity,HasDraftEntity,IsActiveEntity,PLANNER,PLANNING_NOTE,PRODUCT_ID_ID,PROMOTION_DATE,PROMOTION_PRICE,PROMOTION_QTY,PROMOTION_TYPE,SALES_RED_FUTR_PERCENTAGE,SALES_RED_FUTR_PRD,SALES_RED_PREV_PERCENTAGE,SALES_RED_PREV_PRD',
  '$expand': 'DraftAdministrativeData($select=DraftIsCreatedByMe,DraftUUID,InProcessByUser)'
}
[cds] - POST /sap/opu/odata/sap/API_IBP_PROMOTIONS/$batch
[cds] - > READ BTPPROMO {
  '$select': 'ID,PRDID',
  '$orderby': 'PRDID',
  '$skip': '0',
  '$top': '64'
}
[remote] - Error: Error during request to remote service: Request failed with status code 400
    at createError (/home/user/projects/sap-ibp-promotions/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/home/user/projects/sap-ibp-promotions/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/home/user/projects/sap-ibp-promotions/node_modules/axios/lib/adapters/http.js:269:11)
    at IncomingMessage.emit (events.js:412:35)
    at endReadableNT (internal/streams/readable.js:1317:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  config: {
    url: '/BTPPROMO?$select=ID,PRDID&$top=64&$orderby=PRDID%20asc,ID%20asc',
    method: 'get',
    proxy: false,
    baseURL: 'https://<Host>:<Port>.ondemand.com/sap/opu/odata/IBP/PLANNING_DATA_API_SRV',
    timeout: 60000,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    data: undefined
  },
  request: {
    method: 'GET',
    url: 'https://<Host>:<Port>.ondemand.com/sap/opu/odata/IBP/PLANNING_DATA_API_SRV/BTPPROMO?$select=ID,PRDID&$top=64&$orderby=PRDID%20asc,ID%20asc',
    headers: {
      Accept: 'application/json,text/plain',
      authorization: 'Basic ...',
      'accept-language': 'en-GB',
      'x-correlation-id': '8ac14c9b-abbf-4d1a-8d17-e267af65d173',
      'User-Agent': 'axios/0.21.4'
    }
  },
  response: {
    status: 400,
    statusText: 'Bad Request',
    headers: {
      'set-cookie': [
        'sap-usercontext=sap-client=100; path=/',
        'SAP_SESSIONID_BBT_100=Ag28-2bFmWeUsk0xsuO35gAEJwVrJxHssTX6Fj4KKec%3d; path=/; secure; HttpOnly'
      ],
      'content-type': 'application/json;charset=utf-8',
      'content-length': '867',
      dataserviceversion: '1.0',
      'sap-server': 'true',
      'sap-perf-fesrec': '539295.000000',
      'x-content-type-options': 'nosniff',
      'strict-transport-security': 'max-age=31536000; includeSubDomains',
      'x-xss-protection': '1; mode=block'
    },
    body: {
      error: {
        code: 'SY/530',
        message: {
          lang: 'en',
          value: 'You need authorization to display this object.'
        },
        innererror: {
          application: {
            component_id: 'SCM-IBP-INT-ODT',
            service_namespace: '/IBP/',
            service_id: 'PLANNING_DATA_API_SRV',
            service_version: '0001'
          },
          transactionid: '3372965542570170E0061D08C5F7A588',
          timestamp: '20220101171939.5087290',
          Error_Resolution: {
            SAP_Transaction: 'For backend administrators: use ADT feed reader "SAP Gateway Error Log" or run transaction /IWFND/ERROR_LOG on SAP Gateway hub system and search for entries with the timestamp above for more details',
            SAP_Note: 'See SAP Note 1797736 for error analysis (https://service.sap.com/sap/support/notes/1797736)'
          },
          errordetails: [
            {
              ContentID: '',
              code: '',
              message: 'You need authorization to display this object.',
              propertyref: '',
              severity: 'error',
              transition: false,
              target: ''
            }
          ]
        }
      }
    }
  },
  isAxiosError: true,
  correlationId: '8ac14c9b-abbf-4d1a-8d17-e267af65d173'
}
[cds] - Error: Error during request to remote service: Request failed with status code 400
    at run (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/libx/_runtime/remote/utils/client.js:248:25)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async RemoteService.<anonymous> (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/libx/_runtime/remote/Service.js:179:20)
    at async next (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/lib/serve/Service-dispatch.js:74:17)
    at async RemoteService.handle (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/lib/serve/Service-dispatch.js:72:10)
    at async RemoteService.handle (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/libx/_runtime/remote/Service.js:230:22)
    at async next (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/lib/serve/Service-dispatch.js:74:17)
    at async ApplicationService.handle (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/lib/serve/Service-dispatch.js:72:10)
    at async _readCollection (/home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/handlers/read.js:268:19)
    at async /home/user/projects/sap-ibp-promotions/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/handlers/read.js:457:16 {
  statusCode: 502,
  innererror: Error: Error during request to remote service: Request failed with status code 400
      at createError (/home/user/projects/sap-ibp-promotions/node_modules/axios/lib/core/createError.js:16:15)
      at settle (/home/user/projects/sap-ibp-promotions/node_modules/axios/lib/core/settle.js:17:12)
      at IncomingMessage.handleStreamEnd (/home/user/projects/sap-ibp-promotions/node_modules/axios/lib/adapters/http.js:269:11)
      at IncomingMessage.emit (events.js:412:35)
      at endReadableNT (internal/streams/readable.js:1317:12)
      at processTicksAndRejections (internal/process/task_queues.js:82:21) {
    config: {
      url: '/BTPPROMO?$select=ID,PRDID&$top=64&$orderby=PRDID%20asc,ID%20asc',
      method: 'get',
      proxy: false,
      baseURL: 'https://<Host>:<Port>.ondemand.com/sap/opu/odata/IBP/PLANNING_DATA_API_SRV',
      timeout: 60000,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      data: undefined
    },
    request: {
      method: 'GET',
      url: 'https://<Host>:<Port>.ondemand.com/sap/opu/odata/IBP/PLANNING_DATA_API_SRV/BTPPROMO?$select=ID,PRDID&$top=64&$orderby=PRDID%20asc,ID%20asc',
      headers: {
        Accept: 'application/json,text/plain',
        authorization: 'Basic ...',
        'accept-language': 'en-GB',
        'x-correlation-id': '8ac14c9b-abbf-4d1a-8d17-e267af65d173',
        'User-Agent': 'axios/0.21.4'
      }
    },
    response: {
      status: 400,
      statusText: 'Bad Request',
      headers: {
        'set-cookie': [
          'sap-usercontext=sap-client=100; path=/',
          'SAP_SESSIONID_BBT_100=Ag28-2bFmWeUsk0xsuO35gAEJwVrJxHssTX6Fj4KKec%3d; path=/; secure; HttpOnly'
        ],
        'content-type': 'application/json;charset=utf-8',
        'content-length': '867',
        dataserviceversion: '1.0',
        'sap-server': 'true',
        'sap-perf-fesrec': '539295.000000',
        'x-content-type-options': 'nosniff',
        'strict-transport-security': 'max-age=31536000; includeSubDomains',
        'x-xss-protection': '1; mode=block'
      },
      body: {
        error: {
          code: 'SY/530',
          message: {
            lang: 'en',
            value: 'You need authorization to display this object.'
          },
          innererror: {
            application: {
              component_id: 'SCM-IBP-INT-ODT',
              service_namespace: '/IBP/',
              service_id: 'PLANNING_DATA_API_SRV',
              service_version: '0001'
            },
            transactionid: '3372965542570170E0061D08C5F7A588',
            timestamp: '20220101171939.5087290',
            Error_Resolution: {
              SAP_Transaction: 'For backend administrators: use ADT feed reader "SAP Gateway Error Log" or run transaction /IWFND/ERROR_LOG on SAP Gateway hub system and search for entries with the timestamp above for more details',
              SAP_Note: 'See SAP Note 1797736 for error analysis (https://service.sap.com/sap/support/notes/1797736)'
            },
            errordetails: [
              {
                ContentID: '',
                code: '',
                message: 'You need authorization to display this object.',
                propertyref: '',
                severity: 'error',
                transition: false,
                target: ''
              }
            ]
          }
        }
      }
    },
    isAxiosError: true,
    correlationId: '8ac14c9b-abbf-4d1a-8d17-e267af65d173'
  },
  id: '1970986',
  level: 'ERROR',
  timestamp: 1641057579555
}
Although when I am checking the external odata service its giving me expected result.

0 Likes

Accepted Solutions (1)

Accepted Solutions (1)

SchiwekM
Product and Topic Expert
Product and Topic Expert

Hi Ahmed,

here is the combined solution from the comments above, for a better documentation:

1. Change Product_ID and Customer_ID to the following:

   customerIDs : Composition of many CustomerReference on customerIDs.parent = $self; 
productIDs : Composition of many ProductReference on productIDs.parent = $self;

2. Add the CustomerReference and ProductReference entity to your schema:

@assert.unique: { 
customer: [ custID, parent ],
}
entity CustomerReference : cuid {
parent : Association to one Promotions;
custID : Association to one Customer;
}
@assert.unique: {
product: [ prodID, parent ],
}
entity ProductReference : cuid {
parent : Association to one Promotions;
prodID : Association to one Product;
}

3. Add the Customer and the Product as projections on the BTPPROMO entity to your schema

@cds.persistence.skip
entity Customer as projection on external.BTPPROMO {
key CUSTID,
CUSTDESCR,
BASELINEFCSTQTY @UI.Hidden,
}
@cds.persistence.skip
entity Product as projection on external.BTPPROMO {
key PRDID,
PRDDESCR,
BASELINEFCSTQTY @UI.Hidden,
}

4. It is important to add the Customer and Product entity also to your service, so they are exposed and can be accessed. The BTPPROMO entity is also added, else the projections wouldn't work.

   @readonly entity BTPPROMO as projection on external.BTPPROMO; 
@readonly entity Customer as select from PromService.Customer;
@readonly entity Product as select from PromService.Product;

5. Add after read handler for customer and product, to filter for unique entities. The method is probably not the best, but should be sufficient.

const {Customer, Product} = srv.entities;
srv.on(['READ'],[Customer], async (response, req) => {
let response = await service.tx(req).run(req.query);
response = response.reduce((accumalator, current) => {
if (
!accumalator.some(
(item) => item.CUSTID === current.CUSTID && item.CUSTDESCR === current.CUSTDESCR
)
) {
accumalator.push(current);
}
return accumalator;
}, []);
req.results = response;
return response;
});
srv.on(['READ'],[Product], async (response, req) => {
let response = await service.tx(req).run(req.query);
response = response.reduce((accumalator, current) => {
if (
!accumalator.some(
(item) => item.PRDID === current.PRDID && item.PRDDESCR === current.PRDDESCR
)
) {
accumalator.push(current);
}
return accumalator;
}, []);
req.results = response;
return response;
});

6. Add ValueList annotations to the Customer and Product Reference entity. The BaseLineFCSTQTY property is requested, because it is listed as a parameter, but it will not be visible, because it is annotated with '@UI.Hidden' in the schema above.

annotate CustomerReference with { 
custID @Common : {
ValueList : {
CollectionPath : 'Customer',
Parameters : [
{
$Type : 'Common.ValueListParameterOut',
LocalDataProperty : custID_CUSTID,
ValueListProperty : 'CUSTID',
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'CUSTDESCR',
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'BASELINEFCSTQTY',
},
],
}
}
};
annotate ProductReference with {
prodID @Common : {
ValueList : {
CollectionPath : 'Product',
Parameters : [
{
$Type : 'Common.ValueListParameterOut',
LocalDataProperty : prodID_PRDID,
ValueListProperty : 'PRDID',
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'PRDDESCR',
},
{
$Type : 'Common.ValueListParameterDisplayOnly',
ValueListProperty : 'BASELINEFCSTQTY',
},
],
}
}
};

7. Add the multi input fields to your section of your Fiori app.

annotate service.Promotions with @( 
UI.FieldGroup #test : {
Data : [
{
Label : '{i18n>Customers}',
Value : customerIDs.custID_CUSTID,
},
{
Label : '{i18n>Products}',
Value : productIDs.prodID_PRDID,
},
],
},
UI.Facets : [
{
$Type : 'UI.ReferenceFacet',
Target : '@UI.FieldGroup#test',
Label : 'Multi input field',
},
]
);

Best regards,

Marten

jessicademarchi
Product and Topic Expert
Product and Topic Expert
0 Likes

Hi, smarten

Could you please check my question to see if you can help me?

https://answers.sap.com/questions/13796941/filter-using-value-list-value-help.html

Thank you!!!

Answers (0)