June 30, 2023

SAP Commerce Product Review And Rating | Product Reviews Rating in Hybris

SAP Commerce Product Review And Rating | Product Reviews Rating in Hybris

 SAP Commerce (formerly known as SAP Hybris Commerce) provides various features and capabilities for implementing product reviews and ratings on an e-commerce platform. The implementation typically involves the following components and steps:

1. Data Model:

   - Review: This represents an individual review written by a customer. It includes attributes such as the reviewer's name, date of the review, rating, comments, etc.

   - Rating: This represents the overall rating given by customers for a product. It can be an average of all the individual ratings received.

2. User Interface:

   - Review Submission Form: You need to design a user-friendly form where customers can submit their reviews. The form should include fields for the rating (e.g., star rating) and a comment box for additional feedback.

   - Review Display: Implement a section on the product page where customer reviews are displayed. Each review should show the rating, reviewer's name, date, and comments. Optionally, you can include features like sorting reviews by rating or date, pagination, and the ability to upvote or downvote reviews.

3. Backend Services:

   - Review Creation: When a customer submits a review, you need to create a service that receives the form data and stores it in the database. Validate the data to ensure it meets the required criteria (e.g., rating within a specific range).

   - Review Retrieval: Implement a service to retrieve the reviews for a specific product. This service should query the database and return the relevant review data.

   - Rating Calculation: To determine the overall product rating, you can calculate the average rating based on the individual ratings received for that product. This can be done using a service or through database queries.

4. Integration with Product Pages:

   - Modify the product detail page template to display the overall rating for each product. This rating can be dynamically updated whenever a new review is submitted.

   - Add a link or button on the product page that directs customers to the section displaying reviews.

5. Moderation and Management:

   - Implement moderation features to review and approve customer submissions before they are publicly displayed. This step helps in maintaining the quality and appropriateness of reviews.

   - Provide an administration interface where site administrators can manage reviews, edit or delete them if necessary.

6. Analytics and Reporting:

   - Track and analyze review data to gain insights into customer sentiment, product performance, and areas for improvement.

   - Generate reports on customer ratings and reviews to understand trends, identify popular products, and make data-driven decisions.


It's worth noting that the implementation details may vary depending on your specific requirements and the version of SAP Commerce you are using.

June 16, 2023

SAP Commerce Hybris Backoffice Editor Area Enable Attribute Selection On Different value

 In the Hybris backoffice editor area, you can enable attribute selection based on different value contexts by following these steps:

1. Log in to the Hybris backoffice.

2. Navigate to the "Type System" section. This is typically found in the "System" tab or a similar location, depending on your Hybris version and configuration.

3. In the "Type System" section, locate and select the item type for which you want to enable attribute selection based on value contexts. For example, if you want to enable attribute selection for a product, select the "Product" item type.

4. Once you have selected the item type, you will see a list of attributes associated with that item type.

5. Locate the attribute for which you want to enable value context-based selection and click on it to edit its properties.

6. In the attribute properties editor, look for the option related to value context or selection context. The exact name and location of this option may vary depending on your Hybris version and configuration.

7. Enable the value context or selection context option for the attribute. This option allows you to define different value contexts based on which the attribute selection will vary.

8. Save the changes you made to the attribute properties.

Once you have enabled attribute selection by value context for an attribute, you can configure the specific value contexts and their corresponding attribute values in other parts of the Hybris backoffice, such as the "Classification" or "Product Cockpit" sections. The exact steps for configuring value contexts and their values may vary depending on your Hybris version and configuration.

June 12, 2023

Deploying your SAP Commerce Application from GIT hub to CCV2 Cloud Portal ?

 To deploy a Hybris application code base from GitHub to the CCV2 portal, you can follow these general steps:

1. Set up the CCV2 environment: Make sure you have the necessary access rights and permissions to deploy applications to the CCV2 portal. Obtain the required credentials and access information from your system administrator or cloud provider.

2. Clone the Hybris code repository: On your local machine or development environment, clone the Hybris application code base from the GitHub repository. Use the appropriate Git command to clone the repository to your local directory.

   ```

   git clone <repository-url>

   ```

3. Build the Hybris application: Once you have the code base on your local machine, navigate to the Hybris project's root directory. Use the build commands specific to your Hybris version and setup to compile and build the application.

   ```

   cd <hybris-project-directory>

   ./hybrisserver.sh build

   ```

4. Package the application: After the build process is complete, create a deployment package for the Hybris application. This package will be used to deploy the application to the CCV2 portal.

   ```

   ./hybrisserver.sh package

   ```


5. Connect to the CCV2 portal: Use the appropriate command-line interface or web-based interface to connect to the CCV2 portal. Provide the necessary login credentials and navigate to the application deployment section.

6. Upload the deployment package: In the CCV2 portal, locate the option to upload an application package. Select the package you created in the previous step and upload it to the portal. The upload process may take some time depending on the size of the package.

7. Configure the deployment: Once the package is uploaded, you may need to configure various deployment settings, such as specifying the runtime environment, configuring database connections, and setting up any required dependencies. Follow the instructions provided by the CCV2 portal interface to complete the deployment configuration.

8. Deploy the application: After the configuration is complete, initiate the deployment process. This process will take care of deploying the Hybris application code to the CCV2 portal and setting up the necessary infrastructure. Monitor the deployment progress and ensure that it completes successfully.

9. Test the deployed application: Once the deployment is finished, access the deployed Hybris application through the provided URL or endpoint. Perform thorough testing to ensure that the application is functioning correctly in the CCV2 environment.

These steps provide a general overview of deploying a Hybris application code base to the CCV2 portal.

May 31, 2023

How to install yForms in SAP Commerce, Step by Step process

How to install yForms in SAP Commerce, Step by Step process

yForm provides a user-friendly interface for data capture and allows businesses to define the structure of the form, specify validation rules, and define actions to be performed upon form submission. The framework simplifies the process of creating and managing forms within the Hybris Commerce platform, enabling businesses to effectively collect and utilize data.

To install yForms in SAP Hybris, you need to follow these general steps:

1. Obtain the yForms Extension:

- Check if the yForms extension is available as a separate extension from SAP Hybris or a third-party provider.

- Download the yForms extension or obtain it from a version control system if it is part of your project repository.

2. Include the yForms Extension in Your Project:

- Copy the yForms extension folder into the `hybris/bin/custom` directory of your SAP Hybris installation.

- Add the yForms extension to your project's `localextensions.xml` file located in the `hybris/config` directory.

- Include the yForms extension in the `extensioninfo.xml` file of your project's extension configuration.

3. Build and Deploy the Project:

- Navigate to the `hybris/bin/platform` directory using the command line.

- Run the `ant clean all` command to clean and build the project.

- Once the build process is complete, run the `./hybrisserver.sh` (or `.bat` for Windows) command to start the Hybris server.

4. Verify the Installation:

- Access the Hybris Administration Console (HAC) by opening a web browser and entering the URL `http://localhost:9001/hac`.

- Log in using your HAC credentials.

- Check if the yForms extension is listed in the Installed Extensions section of the HAC.

Please note that the installation process may vary depending on the specific version of SAP Hybris you are using and any customizations in your project. 

It's recommended to consult with your development team, refer to the documentation, and follow best practices while installing and configuring extensions in SAP Hybris.


What are yForm in SAP Commerce ? How to use yForm in SAP Commerce ?

 In simple words, yForms in Hybris refer to a form-based framework used to create and manage dynamic forms in the Hybris Commerce platform. It provides a flexible way to define and configure forms for capturing and processing data. With yForms, you can design forms with various input fields such as text fields, checkboxes, dropdowns, and radio buttons.

yForms offer a user-friendly interface for capturing data from customers or users. The captured data can be used for various purposes like user registration, product inquiries, feedback forms, or any other data collection needs within a Hybris-based application

The yForm framework allows you to define the structure of the form, specify validation rules for the input fields, and define actions to be performed upon form submission. It provides capabilities for customizing the look and feel of the form, handling user input, and processing the submitted data.

Overall, yForms simplify the process of creating and managing forms within the Hybris Commerce platform, enabling businesses to collect and utilize data effectively for various purposes.


How to use yForm in SAP Commerce/SAP Hybris ?

To use yForms in SAP Hybris, you need to follow certain steps. Here's a general overview of the process:

1. Define the Form:

- Identify the data you want to capture using the form.

- Define the structure of the form by specifying the input fields, labels, and any other relevant attributes.

- Determine the validation rules for each input field, such as required fields, data formats, or length restrictions.

2. Create the Form Template:

- Design the visual layout and appearance of the form using HTML, CSS, and SAP Hybris Tag Libraries (such as yhtml, yform, etc.).

- Define the mapping between the form fields and the data model entities in SAP Hybris.

3. Configure the Form Actions:

- Specify the actions to be performed upon form submission, such as storing the data in the database, sending notifications, or triggering workflows.

- Define any additional business logic or workflows associated with the form submission.

4. Integrate the Form in a Hybris Application:

- Identify the page or component where you want to display the form within your Hybris application.

- Use the appropriate tag library and tags to include the form template and bind it to the relevant data models.

5. Customize the Form Behavior (Optional):

- Customize the form behavior by implementing event handlers or listeners.

- Add client-side validation using JavaScript or integrate with server-side validation mechanisms.

6. Test and Deploy the Form:

- Test the form to ensure it functions as expected.

- Deploy the form to your production environment or relevant development/staging environments.


April 26, 2023

Where to test stopword in SOLR admin console once configure in SAP Commerce Hybris?

In Solr, stop words are commonly used to remove certain words from the search query that are too common and do not add much value to the search results. The stop words can be configured in the Solr Admin Console using the "Analysis" feature.

To configure stop words in Solr, you need to select the collection for which you want to configure stop words and modify the analyzer by adding the list of stop words that you want to use. 

To configure stop words in Solr, you can follow these steps:

  1. Open the Solr Admin Console
  2. Select the collection for which you want to configure stop words
  3. Click on the "Analysis" link in the left sidebar
  4. In the "Field" dropdown, select the field for which you want to configure stop words
  5. In the "Analyzer" dropdown, select the analyzer that you want to modify (e.g. "StandardTokenizer")
  6. In the "Filter" section, click on "StopFilter" to expand it
  7. In the "Stop Words" field, add the list of stop words that you want to use, separated by commas (e.g. "a,an,the")
  8. Click on the "Save" button to apply your changes

Here's an example of a Solr query to search for documents containing the word "apple", but excluding documents that contain any of the stop words "a", "an", or "the":

SOLR Query Example :-

q=apple -a -an -the

Note that you need to prefix the stop words with a minus sign (-) to indicate that you want to exclude them from the search.


April 21, 2023

What are Interceptors in SAP Hybris? How many types of Intercepter exist in SAP Hybris?

What are Interceptors in SAP Hybris? 

In SAP Hybris, interceptors are an important feature of the platform that enable you to modify the behavior of certain actions or events in the system. Interceptors are essentially Java classes that are configured to intercept and modify certain operations in the system.

Interceptors are used to implement cross-cutting concerns, such as logging, security, and performance monitoring. They allow you to add functionality to the system without modifying the existing codebase. Instead, interceptors are configured to intercept specific operations, and the functionality is added by modifying the interceptor code.

How many types of Intercepter exist in SAP Hybris?

There are several types of interceptors in SAP Hybris, including:

Before interceptor: This type of interceptor is executed before the main operation and can modify the input parameters or cancel the operation altogether.

After interceptor: This type of interceptor is executed after the main operation and can modify the output parameters or handle exceptions that occurred during the operation.

Around interceptor: This type of interceptor wraps around the main operation and can modify both input and output parameters.

Interceptors are an important aspect of SAP Hybris and can be used to customize and extend the platform's functionality to meet specific business requirements.


SAMPLE CODE :-

public class MyBeforeInterceptor implements Interceptor {

    @Override

    public void beforeInterception(final Context ctx, final InterceptorContext interceptorContext) throws InterceptorException {

        // Do something before the main operation

        System.out.println("Before interceptor executed");

    }

}

In this example, we have defined a before interceptor called MyBeforeInterceptor. This interceptor implements the Interceptor interface and overrides the beforeInterception method, which is called before the main operation.


Inside the beforeInterception method, we can add any logic that we want to execute before the main operation. In this case, we simply print a message to the console.

To use this interceptor, we need to configure it in the interceptor.xml file, like this:

<bean id="myBeforeInterceptor" class="com.example.MyBeforeInterceptor"/>

<interceptor name="myInterceptorChain" default="true">

    <before>

        <bean class="com.example.MyBeforeInterceptor"/>

    </before>

    <target>

        <!-- Main operation -->

    </target>

    <after>

        <!-- After interceptors -->

    </after>

</interceptor>


In this configuration, we define a bean for our interceptor and then add it to an interceptor chain called myInterceptorChain. The before element specifies that this interceptor should be executed before the main operation.

When the main operation is executed, the interceptor chain is triggered and the beforeInterception method of our interceptor is called before the main operation. We can then add any logic that we want to execute before the main operation




April 11, 2023

AEM- SAP Commerce Integration

 

AEM Hybris Endpoint

The AEM Hybris endpoint is the one handling the category importer, PLP/Global search and PDP on the AEM site. By default is the set to point dev on code base, but to change it to stage or any other instance, the steps to configure it are:

  • Go to http://localhost:4502/system/console/configMgr

  • Search for: SMITH - Hybris Connection Service

  • Change Hybris Server URL to any other instance URL.


Apache Endpoint

The apache Hybris endpoint is going to handle all the Hybris calls, logins and the rest of commerce interactions for local.kennametal.com and local.widia.com, by default is configured to point dev, but you can change it to any other instance you want following the next steps:

  • Go to /usr/local/etc/httpd/env/env.conf.local

  • Find Define HYBRIS_DOMAIN

  • Set it to any other instance URL you want to work with.

April 2, 2023

SAP Hybris/SAP Commerce Invoice Integration With S4


SAP Hybris/SAP Commerce Invoice Integration With S4 

The Integration is to connect with S4 Hana System via SAP CPI and to get order-related details like 

Order Status, 

Invoice Document, 

Delivery Document, 

Order Confirmation and

Order Acknowledge Document.

When we placed the Order from B2B Side, Order will reach to S4 Hana via CPI. On S4 Hana system the interim order gets created which get converted to sales order once the business acknowlege it for the interim order the sales order get created based upon the Q factor check in S4, like product availablity, Inventory, Price logic execution, for the sale order have its own order status and sales order document.

We have to show same order status on Order History Page and Order Details Page FOR SALES ORDER. Also document related information we will show on order details page.

Invoice Integration is a synchronous integration, real time the call is been made to S4 passing the sale order no, to get the information back to Commerce from S4.

ODATA URL Patterns :- 

https://*-*.hcisbt.eu1.hana.ondemand.com/http/Commerce/S4/InvoiceNumber/Enviroment Id

Request Body which we will pass to CPI  is from SAP Hybris/SAP Commerce

{

  "sapOrderCode" : "130320"

}


Response :-

Response body will get order status and delivery ASN, invoice document number, etc as string for all  document present in S4 Hana system

From B2B Side we will convert Hex String into PDF and same we will show on B2B Side.

OOTB -> OrderPopulator we need to override – To show the document related information and keep it in target object, later in service layer, we can write the logic to convert hex to PDF document dynamically.


March 24, 2023

SAP Commerce/SAP Hybris Product Master Data Load(Inbound Integration Call)

 As part of SAP Commerce/SAP Hybris customer requirement solutioning, product master data load is one crucial topic,  

How the product master data will come? 

What are the field product master data will have? 

How data field will be mapped to SAP Commerce/SAP Hybris inbound integration object?

Let's talk on this point:- How well we can do it effectively.

SAP Commerce/SAP Hybris OOTB has most of the inbound integration objects and extensions which support them.

The extension list is as:-

         <extension name='inboundservices'/>

        <extension name='outboundservices'/>

        <extension name='integrationservices'/>

        <extension name='odata2services'/>

        <extension name='integrationmonitoringbackoffice'/>

        <extension name='integrationbackoffice'/>

        <extension name='outboundsyncbackoffice'/>

        <extension name='outboundsync'/>

So when you configure this list of extensions, after doing an update or initialize, in back office you will see the Integration UI Tool option.



In the Integration UI Tool, all the integration objects for inbound/outbound will be available.

In SAP Hybris/SAP Commerce product data load integration object name is InboundProduct.

InboundProduct implicitly takes the product model into consideration.
Now we have three items types, which play a significant role:-
1. IntegrationObject -> hear integration name is defined.
2. IntegrationObjectItem - hear integration data model name is defined and attribute mapping context is defined like  ALL_SUB_AND_SUPER_TYPES
3. IntegrationObjectItemAttribute -  hear Integration object name is mapped to Item type defined in Integration object items, and list of attributes.

Ex: -
INSERT_UPDATE IntegrationObject; code[unique = true]; integrationType(code) 
; InboundProduct; INBOUND 

INSERT_UPDATE IntegrationObjectItem; integrationObject(code)[unique = true]; code[unique = true]; type(code); root[default = false]; itemTypeMatch(code) 
; InboundProduct ; Catalog              ; Catalog              ; ; ALL_SUB_AND_SUPER_TYPES ;  
; InboundProduct ; Category              ; Category              ; ; ALL_SUB_AND_SUPER_TYPES ;  
; InboundProduct ; Unit                  ; Unit                  ; ; ALL_SUB_AND_SUPER_TYPES ;  
; InboundProduct ; Warehouse            ; Warehouse            ; ; ALL_SUB_AND_SUPER_TYPES ;  

INSERT_UPDATE IntegrationObjectItemAttribute; integrationObjectItem(integrationObject(code), code)[unique = true]; attributeName[unique = true]; attributeDescriptor(enclosingType(code), qualifier); returnIntegrationObjectItem(integrationObject(code), code); unique[default = false]; autoCreate[default = false] 
; InboundProduct:Catalog              ; id                      ; Catalog:id                      ;                                      ; ;  
; InboundProduct:Category              ; code                    ; Category:code                  ;                                      ; ;  
; InboundProduct:Category              ; catalogVersion          ; Category:catalogVersion        ; InboundProduct:CatalogVersion        ; ;  
; InboundProduct:Unit                  ; unitType                ; Unit:unitType                  ;                                      ; ;  
; InboundProduct:Unit                  ; name                    ; Unit:name                      ;                                      ; ;  
; InboundProduct:Unit                  ; code                    ; Unit:code                      ;                                      ; ;  
; InboundProduct:Warehouse            ; code                    ; Warehouse:code                  ;                                      ; true ;  
; InboundProduct:Warehouse            ; name                    ; Warehouse:name                  ;                                      ; ;  
; InboundProduct:Warehouse            ; vendor                  ; Warehouse:vendor                ; InboundProduct:Vendor                ; ;  

NOTE:- SAP Commerce/SAP Hybris OOTB provide all the attribute present in the OOTB data model, but if there is any customer-specific attribute created, then you need to update the impex, create a custom impex, copy the impex from the OOTB, paste it, in custom initial data extension in your relevant package, there define the custom attribute in IntegrationObjectItem and IntegrationObjectItemAttribute type, like present.

Also, you can modify the attribute from the integration UI tool of SAP Commerce/SAP Hybris from backoffice, like Unique to true, auto create, generate, and rename it adhocly from the back-office.

Once this activity is completed, then you can copy the rest OData endpoint, which the middleware has to hit, keep note all the mapping of incoming data from a legacy application like S4 Hana, SAP ECC, Oracle apps, to be done in Middleware like SAP CPI, Mule Soft, when the product data will get transition to SAP Commerce acceptable format.

Mandatory Attributes sent from S4 OTC Team/SAP ECC Team

  • Product Code(Unique)

  • Catalog Version

  • Qualifier


This are mandatory attribute, without which the product creation will fail, as they are unique equals true.

WorkFlow:

  • S4 OTC will send the material master to CPI(Middleware)

  • CPI is going to send the Product Data to B2B environments using oAuth Authentication.

  • Ideally, the received product will be in Staged Version.

  • Catalog version will be <catalogName>ProductCatalog.

  • Once, B2B receives the product data following operation are performed after we persist : 

    • Update all the classification classes to the product, so that the product manager can easily update the values from backoffice.

    • Default List Price will be created.

    • Note : All the UOM details for each product will be coming from OTC.

  • After catalog sync, the product will be displayed on the sit

March 20, 2023

SAP Hybris-SAP Commerce Cloud Development Process Guide Lines Should Be Followed

 

  • A Developer has to follow the below process in his/her development for better tracking of tickets.

  • Developers has to cross-check below items before picking a ticket:

    1. Fix Version - should be the current sprint

    2. Sprint - should be the current sprint

    3. Product Owner

    4. Work Stream - SAP Commerce or AEM

    5. Priority - ticket has to be prioritized by BA or Scrum Master

  • Once we have all of these for ticket. Developer has to do below tasks:

    1. Analysis, Technical Feasibility - Developer will analyze ticket and come up with any doubts or if something is technically not possible or any other better solution

    2. Tech Design Preparation and Approval Process - Based on the complexity of the stories, technical design might be needed. Below criteria can be used to determine the need of tech designs. Once the tech design is completed, assign to the architects for review and approval. Create a subtask for the tech approval task and keep Story as Tech Approval status. Subtask should be In Review when assigning for review with proper comments.. Once review is completed and approves, status should be Closed with proper comment.

      • New EPIC

      • Performance Improvement changes as it is altering the existing design

      • Any change affecting both Hybris and AEM and/or SAP.

      • Any major technical introduction like Active Directory Enhancement.

      • Any implementation with the introduction of new libraries.

    3. Update Estimates - Developer has to come up with estimate on number of hours required to complete given ticket along with Sprint points (if this ticket is a story)

    4. Update Labels (If applicable like Hybris_BE, Hybris_FE)

    5. Create any sub tasks (if required, have them added to sprint by Scrum Master)

  • After this, Developer will change ticket status to In Progress. Developer has to update time spent on each ticket for the day (8hrs per day, 40Hrs per week) such that we can have track of ticket

  • Make sure Sonarlint setup is done in your IDE and make sure it is working fine.

  • For any impex related changes, do not copy paste from older impexes as those details might have outdated in later releases. In the impexes, add the attributes which is supposed to change as part of your current story. Have extra care on introducing new changes to solrindexedproperties/facets and webservice operations related item types.

  • Once development is done, raise PR and assign to the respective lead. If a second round of review is needed, leads should assign to architect side. Once PR is approved, assign to the merger/release management lead for the merging activity.


Hope this step, help in formulating the development to review process which should be followed in general for SAP Hybris/ SAP Commerce Cloud development of stories.

March 3, 2023

SAP Commerce/SAP Hybris Invoice Integration Approach via SAP CPI Middleware

When the customer land on the order history page, he clicks on the order -> b2b customer land on the order detail page, a business can ask to show the order invoice PDF document, delivery ASN document, Order confirmation & Order acknowledgment PDF document, which they have in S4

Approach:- 

SAP Commerce/SAP Hybris <-----> SAP CPI <------> S4 System

 Integration to connect S4 system via CPI to SAP Commerce/SAP Hybris and to get the order-related details like Order status, Invoice document, Delivery document, Order confirmation and Order acknowledgment document.

When we placed the Order from B2B Side, Order will reach S4 via CPI or any middleware which transfers the SAP Hybris request to the respective format of S4, The order will be getting created as Interim Order(Parent Order) in S4.

When the customer representative picks up the order, he will apply some delivery block like Z0, Z1, etc., based upon the request passed in the order Idoc request.

Like if you have any additional fields in SAP Commerce/SAP Hybris checkout steps, like

1.) price negotiation check box, 

2.) special text field check area.

3.) Price token send to S4(Hidden attribute)

4.) Order as quote indicator. 

We have to show the order status on Order History Page and Order Details Page for the Interim(Parent) order from S4, So basically what the order status is in S4, the same we have to replicate to B2B Channel, via ODATA call, Also PDF document related information we will show on the order details page.

Option available -

1. Direct integration call, from SAP Commerce/SAP Hybris to S4 when the order history page is loading.

 NOTE:- Performance can be affected if there are many orders available, as one by one you need to iterate the order from the order history page and pass it to S4, via middleware.

2. Write a utility job - Cron job, for which we can write a trigger, that runs at the particular time interval which is configured, in the Cron expression.

in Cron job -> we have executed method(Inherits from the implemented OOTB class), where we can write the logic to fetch all the parent orders, in the order model we have SAP order code attribute available, you can check the same in the Administrator tab, of the back office.

Request Body that we will pass to CPI from B2B/B2C SAP Commerce/SAP Hybris

{

     "sapOrderCode": "sap order code reference id"

}

The response body from S4 will get the order status and hex string for all the above-mentioned documents from the S4 system.

From B2B Side we will convert Hex String into PDF and the same we will show on B2B Side dynamically. 

When the order detail page is loaded, in the Order detail response from S4, we will get reference no. for the doc, like for the delivery note, and order confirmation doc reference no, which we need to show on the storefront via real-time integration call.

Now, when viewing the document, the customer has to click on the storefront, where the reference no. is shown.

Request mapping for it, via a Ajax call.

        @ResponseBody

@RequestMapping(value = "/invoicePDFView", method =

{ RequestMethod.POST, RequestMethod.GET })

//produces = MediaType.APPLICATION_JSON_VALUE)

public void invoicePDFView(final String document number, final String sapOrderCode, final String type of document,

final HttpServletRequest request, final HttpServletResponse response) throws DecoderException, IOException


This line of code will decode the hex string --->

 final byte[] decodedHex = org.apache.commons.codec.binary.Hex.decodeHex(documentPDF.toCharArray());

                       if (null != decodedHex && decodedHex.length > 0) {

if (!StringUtils.isEmpty(document name))

{

response.setHeader("Content-Disposition", "inline;filename=" + documentName);

}

response.setDateHeader("Expires", -1);

response.setContentType("application/pdf");

response.getOutputStream().write(decodedHex);

response.getOutputStream().close();

response.getOutputStream().flush();

}


Following above is the sudo logic, which can be used, by the developer and modify it while debugging.


Thanks for reading.





SAP Commerce/Hybris B2B Customer & B2B Unit Onboarding Process

 Today I will be covering the B2B Unit and B2B Customer Onboarding process, for your end client.

Companies are putting a lot of money into making the infrastructure, from long back years, they have built a historic data set, for 

1. products, 

2. customers, 

3. content, 

4. product prices, 

5. their manufacturing warehouse/plant in SAP, 

6. discounts, 

7. promotion

and many more.

In this blog, I will be talking about SAP Commerce/SAP Hybris technical requirements which most customers have when we implement the SAP Commerce/SAP Hybris omnichannel solution design.

What could be our system? through which we will be integrating could be?

1. SAP S4 System.

2. SAP ECC System.

3. MDG System.

4. Oracle ERP System.

These are a few common systems, most of the legacy customers, we say legacy data.

Now SAP Commerce/SAP Hybris don't talk to this system directly, as each system has a different format of data they pass and they collect/data transformation, few systems accept data in Idoc format, few systems accept data in EDI format, and few in JSON based format, etc.

SAP Commerce/SAP Hybris has ODATA web service for inbound load requests, Odata are webservice which are Restful webservice.

Inbound Integration -> Data which is receiving to SAP Commerce/SAP Hybris from the Legacy system, basically the source data is getting replicated to SAP Commerce/SAP Hybris system.

In short, between SAP Commerce/SAP Hybris and Legacy system -> we need a middleware who transform the data, SAP Commerce/SAP Hybris accept the data in JSON based format(It is widely used industry acceptable format).

What are the middleware option we have?

1. CPI(SAP Cloud Platform Integrator)

2. PI/PO

3. Data Hub

Both three are equally imported, in transforming/cleaning and discarding data if any.

Lets talk on SAP CPI -> It is cloud based native application, which can dynamically scale up based on load, and accept wide set of data format and convert it into read able format for end system.

SAP Commerce/SAP Hybris <- --Connect to CPI----> SAP CPI <----Webservice/Odata connection--------> SAP S4 System

Now how the connection will work between SAP Commerce/SAP Hybris to SAP CPI system, in SAP Commerce/SAP Hybris, we have OOTB extension, provided in Module package whcih we need to download from SAP portal,

SAP Commerce/SAP Hybris CPI Extension Name

 we have sapcpiadapter extension, saporderexchange extension, saporderexchangeb2b extension etc, using this integration we can implement the CPI connectivity, we only need to configure the Outbound destination URL, and Username & Password, for authentication.

SAP CPI OMM Order conversion service converts OrderModel to SapCpiOrder and OrderCancelRecordEntryModel to List. 

public class SapCpiOmmOrderConversionService implements SapCpiOrderConversionService

in this class we have following method ->  

public SapCpiOrder convertOrderToSapCpiOrder(OrderModel orderModel)  which contain the completed logic for converting the order model to data obect or DTO.

SapCpiOrder sapCpiOrder = new SapCpiOrder();

 Above functionality is for converting the order data model to  CPI standard.

Action class to send the CPI Order Model to CPI odata endpoint -

public class SapCpiOmmOrderOutboundAction extends SapSendOrderToDataHubAction 

public void executeAction(OrderProcessModel process) throws RetryLaterException {


final OrderModel order = process.getOrder();

getSapCpiOutboundService().sendOrder(getSapCpiOrderOutboundConversionService().convertOrderToSapCpiOrder(order)).subscribe(

// onNext
responseEntityMap -> {

if (isSentSuccessfully(responseEntityMap)) {

setOrderStatus(order, ExportStatus.EXPORTED);
resetEndMessage(process);
LOG.info(String.format("The OMM order [%s] has been successfully sent to the SAP backend through SCPI! %n%s",
order.getCode(), getPropertyValue(responseEntityMap, RESPONSE_MESSAGE)));

} else {

setOrderStatus(order, ExportStatus.NOTEXPORTED);
LOG.error(String.format("The OMM order [%s] has not been sent to the SAP backend! %n%s",
order.getCode(), getPropertyValue(responseEntityMap, RESPONSE_MESSAGE)));

}

final String eventName = new StringBuilder().append(SapOrderExchangeActionConstants.ERP_ORDER_SEND_COMPLETION_EVENT).append(order.getCode()).toString();
getBusinessProcessService().triggerEvent(eventName);

}

// onError
, error -> {

setOrderStatus(order, ExportStatus.NOTEXPORTED);
LOG.error(String.format("The OMM order [%s] has not been sent to the SAP backend through SCPI! %n%s", order.getCode(), error.getMessage()), error);

final String eventName = new StringBuilder().append(SapOrderExchangeActionConstants.ERP_ORDER_SEND_COMPLETION_EVENT).append(order.getCode()).toString();
getBusinessProcessService().triggerEvent(eventName);

}

);

}













February 28, 2023

How to setup the SAP Hybris application in IntelliJ software?

 In this blog, I will guide how to do the SAP Hybris application setup in Intellij Version.

1. Download the latest version of IntelliJ from the JetBrains site, or just write Intellij download on google search bar.

2. Download the latest version of Intellij, in new version you will get new feature, which will help in searching, finding, and auto suggestion for best coding practices.

3. You should have JDK 11, if you are using the SAP Hybris/SAP Commerce till 2011 version, and if you are using 2205 Version+ then you need JDK 17 in you local.

4. Setup the path in environment variable, in the path directory, and the path till /bin from the JDK.

5. Open IntelliJ, and press the ctrl+shift+a keys, and write project from the existing source.

6. Go to the directory where the SAP Hybris is there, till /bin/platform package, and click OK.

7. Now you should see the Hybris project import, If you are not seeing it, then you need to install the plugin "Integration From SAP Commerce"

8. Path to install the plugin is - in IntelliJ open file ->  setting -> plugins -> search for "Integration From SAP Commerce" -> click on install and apply -> restart the IDE.

Intellij SAP Hybris Plugin





February 17, 2023

How to Export Order in CSV or XLS file in SAP Commerce Cloud/SAP Hybris Application?

 In Commerce/Hybris OOTB, support export API, to export the job via utility job.

Impex export is also one of the most common ways of doing the export of order data type into CSV, we only need to put the column name of order data type which we need to export.

Export script can be easily identified from backoffice -> scripting tool -> export button, search for Insert_Update Order clause and put in HAC to export.

1.      Go to Backoffice-> System -> Tools -> Script Generator -> Click on Generate button.

รจ We will get all the scripts syntax for export

1.      Copy all and choose the required syntax as we need the impex for order.

2.      Syntax:

# ---- Extension: core ---- Type: Order ----

"#% impex.setTargetFile( ""Order.csv"" );"

insert_update Order;&Item;Europe1PriceFactory_UDG(code,itemtype(code));Europe1PriceFactory_UPG(code,itemtype(code));Europe1PriceFactory_UTG(code,itemtype(code));Unit(uid);appliedCouponCodes;appliedVoucherCodes;billingTime(code);calculated;cartIdReference;code[unique=true];consentReference;creationtime[forceWrite=true,dateformat=dd.MM.yyyy hh:mm:ss];currency(isocode)[allownull=true];date[allownull=true,dateformat=dd.MM.yyyy hh:mm:ss];deliveryAddress(&Item);deliveryCost;deliveryMode(code);deliveryStatus(code,itemtype(code));description;discountsIncludeDeliveryCost[allownull=true];discountsIncludePaymentCost[allownull=true];entryGroups;expirationTime[dateformat=dd.MM.yyyy hh:mm:ss];exportStatus(code,itemtype(code));fraudulent;globalDiscountValues;globalDiscountValuesInternal;grossWeight;guid;isCompleteDelivery;isProcessedByCronJob;isSpecialPrice;language(isocode);locale;modifiedtime[dateformat=dd.MM.yyyy hh:mm:ss];name;netWeight;net[allownull=true];originalVersion(code,versionID)[forceWrite=true];owner(&Item)[allownull=true,forceWrite=true];parent(code);paymentAddress(&Item);paymentCost;paymentInfo(&Item);paymentMode(code);paymentStatus(code,itemtype(code));paymentTermValue;paymentType(code,itemtype(code));placedBy(uid);potentiallyFraudulent;previousDeliveryMode(code);punchOutOrder;purchaseOrderNumber;quoteDiscountValuesInternal;quoteExpirationDate[dateformat=dd.MM.yyyy hh:mm:ss];quoteReference(code,version);requestedDeliveryDate;salesApplication(code,itemtype(code));sapGoodsIssueDate[dateformat=dd.MM.yyyy hh:mm:ss];sapLogicalSystem;sapPlantCode;sapRejectionReason;sapSalesOrganization(distributionChannel,division,salesOrganization);sapSystemType(code,itemtype(code));schedulingCronJob(code);site(cxConfig(code),uid);specialComment;status(code,itemtype(code));statusInfo;store(uid);subtotal;totalDiscounts;totalPrice;totalTax;totalTaxValues;totalTaxValuesInternal;user(uid)[allownull=true];versionID[forceWrite=true,unique=true];volume;volumeUnit;volumeUnitIso;weightUnit;weightUnitIso;workflow(code)

"#% impex.exportItems( ""Order"" , false );"

 

Here it contains all the attributes of the order table.

  • .      To export the order data for a few/required attributes with query

Try Syntax as: 

"#% impex.setTargetFile( ""Order.csv"" );"

INSERT_UPDATE Order; pk[unique=true]; code[unique=true];

"#% impex.exportItemsFlexibleSearch( ""select {o.pk}, {o.code} from {Order as o}"");"

  First of all export Order with OriginalVersionId, versionId and without  delivery address

So Till now, only order are exported, but we have order to delivery address relation as well, as the part of data migration activity we need to export Order with Delivery address, so we can import it back into different commerce application.

1.      To Export Orders with DeliveryAddress:-

·         First export

  •               B2BUnit, 
  •               B2BCustomer, 
  •               Address, and then 
  •               Orders.

·         As the Delivery address is creating a new field for each order. so update the order with a delivery address

NOTE:  If we import delivery address first it will give error because of owner . Owner is either unit, customer or order itself.

Syntax:  

"#% impex.setTargetFile( ""B2BUnit.csv"" );"
insert_update B2BUnit;&Item;uid[unique=true,allownull=true]
"#% impex.exportItemsFlexibleSearch( ""select {pk} from {B2BUnit}"");"


"#% impex.setTargetFile( ""B2BCustomer.csv"" );"
insert_update B2BCustomer;&Item;uid[unique=true,allownull=true]
"#% impex.exportItemsFlexibleSearch( ""select {pk} from {B2BCustomer}"");"

"#% impex.setTargetFile( ""Address.csv"" );"
insert Address;&pk;appartment;billingAddress[allownull=true];boxno;building;cellphone;company;contactAddress[allownull=true];country(isocode);dateOfBirth[dateformat=dd.MM.yyyy hh:mm:ss];department;district;duplicate;email;fax;firstname;gender(code,itemtype(code));isTemporaryAddress;lastname;latitude;line1;line2;longitude;middlename;middlename2;modifiedtime[dateformat=dd.MM.yyyy hh:mm:ss];original(&pk)[forceWrite=true];phone1;phone2;pobox;postalcode;publicKey;region(country(isocode),isocode);remarks;sapAddressUUID;sapAddressUsage;sapAddressUsageCounter;sapCustomerID;sapMessageFunction;shippingAddress[allownull=true];state;streetname;streetnumber;title(code);town;unloadingAddress[allownull=true];url;visibleInAddressBook;zipbox;owner(&Item)[forceWrite=true]
"#% impex.exportItems( ""Address"" , false );"

How to create custom addon from OOTB addon template in SAP Commerce Cloud/SAP Hybris?

If there is any addon, which is installed on *storefront extension, then we need to uninstall it.

1) Un install the ootb addon by using below command

ant addonuninstall -Daddonnames="commerceorgaddon" -DaddonStorefront.yb2bacceleratorstorefront="*b2bstorefront"

2) Now add the extegen.properties file ootb extention as below,to show this ootb extention as template while creating new ext

extgen.properties(don't need to commit this)

YEXTNAME_TOKEN=commerceorgaddon

YPACKAGE_TOKEN=commerceorgaddonpackage

YMANAGER_TOKEN=CommerceorgaddonManager

YCLASSPREFIX_TOKEN=Commerceorgaddon

YGENERATED_TOKEN=Generated

now add the below property in that ootbs extention extentioninfo.xml

<meta key="extgen-template-extension" value="true"/>

Now create new extention something like commerceorg*addon using ant extgen command and give template as commerceorgaddon

3) Now move the folder to custom folder and add it in localextentions.xml(i.e repalce commerceorgaddon to commerceorg*addon)

4)Now install the newly created addon using below command

ant addoninstall -Daddonnames="commerceorg*addon" -DaddonStorefront.yb2bacceleratorstorefront="*b2bstorefront"

5)Remove the below commerceorgaddon related property in storefront project.properties

*b2bstorefront.additionalWebSpringConfigs.commerceorgbmiaddon=classpath\:/commerceorg*addon/web/spring/commerceorgaddon-web-spring.xml,classpath\:/commerceorgaddon/web/spring/commerceorgaddon-spring-security-config.xml


NOTE - * means your extension name signature.

SAP Commerce Hybris - Narrow Down the Solr Search Criteria & Filter the Result

 

In today word, as the ecommerce industry scope is increasing,business user/customer are coming up with unique feature to optimize the search result for there customer.

Lets take an example, When customer come on to storefront, he goes to search bar and search for some text, based upon that text he entered the auto suggestion keeps telling the relevant suggestion in drop down if auto suggestion feature is turn on in solr now there are two option customer can do :-

1. He select the text from the auto suggestion.

2. Or He add some random text or product name, description which he is faimilar and click on search.


So on both the case, your search page controller will get called and request mapping method signature will be request to full fill the customer request.

As the search is OOTB functionality, in Hybris OOTB/Commerce OOTB by default the free text word is searched across the entire Solr document and based upon relevancy the result is fetch in the form of solr document object which rather then populated in the response object and passed it to frontend with result.

Now How To Narrow Down the Solr Search Criteria?

When the request comes to SearchPageController which extends AbstractSearchPageController, the request textsearch method will get called DefaultSolrProductSearchFacade java class.

Please note : SAP Commerce/SAP Hybris use the Facade design pattern.

Now the facade will call service class from -> getProductSearchService().searchAgain(decodeState(searchState, null), pageableData)

But the return type of facade layer will be ProductSearchPageData Data Transfer Object.

Facade Layer will call Service Layer(DefaultSolrProductSearchService.java class) -> Service will call the strategy class,

 productSearchStrategyFactory.getSearchStrategy().searchAgain(searchQueryData, pageableData);

The strategy class name is DefaultSolrFacetSearchProductSearchStrategy - Now strategy class will call DefautlfacetSearchStrategy.class file.

(above was all techincal to walkthrough the code)

Now there are two approach to solutionize this requirement -

Approch 1. We have the filter queries option, we can create the filter query on selected solr indexer attribute, on which business user want to have search and skip completed document search, becuase free text search have default free text search builder which will internally call factory class which are DisMaxFreeTextQueryBuilder.class, MultiFieldFreeTextQueryBuilder etc.

 Now when you solutionize the requirement, with business user, who need to work closely with them and identify the attribute on which attribute they want search to happen, 

Now again you have to check with client user, 

How the search pattern should happen? is it EXACT Match, Or Wild Card Matchs, Or Phrase Matchs.

This depends on product modelling, SAP Commerce/SAP Hybris provide sufficient product attributes in OOTB, but as per client requirement, we have to create few custom attribute related to product which signifies the client product hireachy.

As when you are solutioning the requirement with client, you need to ask few more question like if end customer search for any text, how the search pattern should be, or you need to break the words and split it then do the search like [0] position word should be getting search in X attribute [1] position word should be getting search in Y attribute and later combine the result and pass it.


Approach 2: We two operator in Solr , which are OR, AND available in FilterQueryOperator, now with this operator there are combination for solr query.

1. ((code_string:textword^70.0) OR (description:textword^70.0) OR (application:textword^70.0) OR (name:textword^70.0))

OR - Operator -> Search the best case if the text word is find out in any attribute then show the result.


2. AND Operator - ((code_string:textword^70.0) AND (description:textword^70.0) AND (application:textword^70.0) AND  (name:textword^70.0)) 

If the value is getting EXACT match for the solr indexer attribute like if you are search for text 'APPLE' then 

((code_string:APPLE^70.0) AND (description:APPLE^70.0) AND (application:APPLE^70.0) AND  (name:APPLE^70.0)) 

code_string : APPLE - if apple is exact match for code string the result will be returned.

so lets assume code_string give value 1, same for other -

((1) AND (1) AND (1)) - then result value is 1 document object.

3.OR in Inner Query AND in Outer Query - 

 Now hear you have to customize the free text query signature - so the query signature get formed in java class FacetSearchQueryBasicPopulator, sample code base -

This is the populater, where the searchQuery get formed.

public void populate(SearchQueryConverterData source, SolrQuery target) {
SearchQuery searchQuery = source.getSearchQuery();
List<String> queries = new ArrayList();
List<String> multiplicativeBoostQueries = new ArrayList();
List<String> additiveBoostQueries = new ArrayList();
this.generateQueryFieldQueries(searchQuery, queries);
this.generateFreeTextQuery(searchQuery, queries);
this.generateRawQueries(searchQuery, queries);
this.generateCoupledFieldQueries(searchQuery, queries);
this.generateBoostQueries(searchQuery, multiplicativeBoostQueries, additiveBoostQueries);
this.populateSolrQuery(target, searchQuery, queries, multiplicativeBoostQueries, additiveBoostQueries);
}

hear - this method you have to override, but if you observe here in the below method, OOTB is calling the free text query builder factory pattern which in turn is calling factory class, where the relevant factory bean get called.

protected void generateFreeTextQuery(SearchQuery searchQuery, List<String> queries) {
if (StringUtils.isNotBlank(searchQuery.getUserQuery())) {
FreeTextQueryBuilder freeTextQueryBuilder = this.getFreeTextQueryBuilderFactory().createQueryBuilder(searchQuery);
String freeTextQuery = freeTextQueryBuilder.buildQuery(searchQuery);
StringBuilder query = new StringBuilder();
query.append("_query_:\"");
query.append(this.escape(freeTextQuery));
query.append('"');
queries.add(query.toString());
}

}

Now we can over ride the OOTB factory and write the custom factory java, extending the OOTB factory class.

Or you over ride this method - 

  String freeTextQuery = freeTextQueryBuilder.buildQuery(searchQuery);

buildQuery - method and write custom method in ABCFacetSearchQueryBasicPopulator.java class and add the dependency in xml file so custom populator will get called. 

you can modify the query and replace the symbol -

((code_string:textword^70.0) OR (description:textword^70.0) OR (application:textword^70.0) OR (name:textword^70.0)) AND ((code_string:textword^70.0) OR (description:textword^70.0) OR (application:textword^70.0) OR (name:textword^70.0))


4. AND in Inner Query OR  in Outer Query - 

((code_string:textword^70.0) AND (description:textword^70.0) AND (application:textword^70.0) AND (name:textword^70.0)) OR ((code_string:textword^70.0) AND (description:textword^70.0) AND (application:textword^70.0) AND (name:textword^70.0))