Unleashing the Potential of SAP S/4HANA Cloud for Asset Maintenance with GO Language for Seamless Extensibility
2023-11-24 17:52:7 Author: blogs.sap.com(查看原文) 阅读量:4 收藏

As a developer I always wanted to learn and explore GO language.I started working on a preventive maintenance scenario for equipment maintenance and develop a side-by-side extension using SAP BTP with SAP S/4HANA Cloud.I found this as a good opportunity to explore GO and create a backend application on SAP BTP with SAP S/4HANA Cloud. In this blog post, we’ll delve into a practical use case centered around equipment maintenance scenarios. We’ll explore the intricacies of our engagement with SAP S/4HANA Cloud APIs and shed some light on the backend application development process using the GO language.

In this blog post we will discuss the use case which involves a technician performing regular equipment checks and creating maintenance requests when repairs are needed. The SAP S/4HANA Cloud facilitates the management of these maintenance requests, allowing the technician to view a list of open maintenance tasks. Once the technician completes the physical repair, he updates the maintenance request status to “Complete,” maintaining a historical record of the repair task.

Figure-1

Development Environment

Let us start from installing Go.

SAP S/4HANA cloud – obtain the necessary credentials by following this guide and test the same.

Developer Extensibility in SAP S/4HANA Cloud

SAP S/4HANA Cloud is an intelligent, next-generation ERP solution that brings efficiency and innovation to businesses worldwide. One of its key features is the Maintenance Notification API, which allows seamless integration and communication with the system, enabling users to manage maintenance tasks and notifications efficiently.

Extensibility in SAP S/4HANA Cloud refers to the ability to customise and extend the functionality of the software to meet specific business requirements without modifying the core codebase. SAP S/4HANA Cloud offers various tools and technologies to enable developers and administrators to achieve extensibility. Let us look at Side-by-Side Extensions in this blog post:

    • Developers can build side-by-side extensions using SAP BTP to add new functionality or integrate third-party applications with SAP S/4HANA Cloud.
    • These extensions can run alongside the core system, reducing the risk of affecting standard operations.

Technical Architecture

Figure-2

REST API Calls to Go Backend:

  • Send REST API requests to the Go backend for various operations, including fetching task data, updating task statuses, and uploading images.
  • The Go backend processes these requests, interacts with SAP S/4HANA Cloud to update the task status and store images, and then responds to the app with the appropriate results.
  • You can use Go to develop custom microservices or serverless functions that run on SAP BTP Kyma, which is connected to SAP BTP. These Go-based microservices can extend the functionality of SAP applications hosted on the SAP BTP.
  • Go’s simplicity and efficiency make it a suitable choice for building lightweight, high-performance microservices that can handle specific tasks or integrate with various SAP BTP services.
  • SAP BTP Kyma’s open architecture and extensibility features make it a powerful platform for deploying and managing Go-based microservices that interact with SAP BTP services and data.

SAP S/4HANA Cloud (Maintenance Management):

  • SAP S/4HANA Cloud serves as the central system for managing maintenance tasks and data.
  • It stores information about maintenance tasks, equipment details, schedules, and task statuses.
  • When the Go backend receives an update request from the mobile app, it communicates with SAP S/4HANA Cloud to perform the necessary data updates.
  • SAP HANA can be used to store historical maintenance data, images, and other relevant information.
  • While SAP S/4HANA Cloud is used for managing maintenance tasks, the data may also be persisted in an SAP HANA database for high-performance data storage and retrieval if required.

This setup allows technicians to efficiently manage maintenance tasks, update task statuses, and provide visual documentation of their work using a web/mobile app while integrating seamlessly with SAP S/4HANA Cloud and potentially persisting data in SAP HANA for further analysis and reporting. The use of Go as the backend technology provides efficiency and scalability for handling REST API requests and interactions with the SAP ecosystem.

In this blog post we will discuss how the server-less functions for Maintenance notification APIs from SAP S/4HANA Cloud are created.

Building Functions in Go for SAP BTP Kyma

In this section, we will delve into creating functions in Go that are deployable on SAP BTP runtime environments like Kyma. These functions will serve as microservices, providing specific functionalities that can be consumed by various applications, including SAP Build Apps.

As we build Go functions to serve as microservices, handling HTTP requests and responses is critical. In this section, we’ll show you how to manage incoming requests, process data, and craft appropriate responses using Go’s capabilities.

Creating Maintenance Notifications

In Go, we can call a function to create a maintenance request using the provided API reference from https://api.sap.com/api/API_MAINTNOTIFICATION/path/post_MaintenanceNotification. Here’s a simplified code snippet to demonstrate the process:

// structure for Maintenance Notification Type
type MRType struct {
	NotificationText string `json: "notificationText"`
	MaintPriority    string `json: "maintPriority"`
	NotificationType string `json: "notificationType"`
	ReportedByUser   string `json: "reportedByUser"`
}

//Function to create Maintenance Notification
func createMaintenanceRequest(w http.ResponseWriter, r *http.Request) {
	var mainReq MRType
	if err := json.NewDecoder(r.Body).Decode(&mainReq); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		log.Println(err)
		return
	}
	defer r.Body.Close()
	outputJson, err := json.Marshal(mainReq)
	if err != nil {
		log.Println(err)
		return
	}
	if err := json.Unmarshal([]byte(outputJson), &mainReq); err != nil {
		// handle errors in deserialization
		panic(err)
	}
	client := &http.Client{}

// http request to get CSRF token
	reqToken, err := http.NewRequest("GET", "<Your SAP S/4HANA Cloud url>/sap/opu/odata/sap/API_MAINTNOTIFICATION/MaintenanceNotification", nil)
	if err != nil {
		fmt.Println(err.Error())
	}
	reqToken.Header.Add("X-CSRF-TOKEN", "FETCH")
	reqToken.Header.Add("Authorization", "Basic <your base64 basic auth credentials>")
	response, err := client.Do(reqToken)
	if err != nil {
		fmt.Errorf("Got error %s", err.Error())
	}
	cookie = response.Cookies() //save cookies

	token = response.Header.Get("x-csrf-token")
	defer response.Body.Close()
	
// build a new request to create Maintenance Notification
	req, err := http.NewRequest("POST", "<Your SAP S/4HANA Cloud url>/sap/opu/odata/sap/API_MAINTNOTIFICATION/MaintenanceNotification", bytes.NewBuffer([]byte(outputJson)))
	if err != nil {
		fmt.Println(err)
	}
	req.Header.Add("Authorization", "Basic <your base64 basic auth credentials>")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Content-Type", "application/json")
	for i := range cookie {
		req.AddCookie(cookie[i])
	}
	req.Header.Add("X-Csrf-TOKEN", token)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	checkResp, _ := io.ReadAll(resp.Body)
	bodyP := string(checkResp)

	xml := strings.NewReader(bodyP)
	json, err := xj.Convert(xml)
	if err != nil {
		// Update error handling
	}
	mrRespBody = json
	w.Write([]byte(bodyP))
}

Please note that the above code is a basic example, and in a real-world scenario, you would need to handle error cases, authentication, and other API-specific details as specified in the API documentation. Additionally, you may need to include appropriate headers or authorization tokens in the HTTP request for successful communication with the API.

By breaking down the code, we aim to offer a practical reference for developers, allowing them to grasp the nuances of working with APIs in the context of SAP S/4HANA Cloud. Feel free to adapt and integrate these snippets into your own projects, fostering a smoother development experience.Similarly, other server less functions could be written as above.

Adding attachment to Maintenance Notification

To add an attachment to a maintenance request using the provided API reference from https://api.sap.com/api/API_CV_ATTACHMENT_SRV/path/post_AttachmentContentSet, we can extend the previous code with an additional function to handle the attachment upload.

First we get the maintenance notification using:

https://api.sap.com/api/API_MAINTNOTIFICATION/path/get_MaintenanceNotification

Then we upload the attachment to that notification.

Get All Open Maintenance Notifications for a specified Date Range

To get maintenance notifications using the provided API reference from https://api.sap.com/api/API_MAINTNOTIFICATION/path/get_MaintenanceNotification, and then filter for open requests within a specific date range, we can create a function in Go to achieve this task.

Moving Maintenance Notification to Complete

To move a maintenance notification to the “Complete” status using the provided API reference from https://api.sap.com/api/API_MAINTNOTIFICATION/path/post_CompleteMaintNotification, we can create a function in Go to achieve this task.

Developer extensibility in SAP S/4HANA Cloud opens up exciting opportunities for learning and growth by encouraging exploration of new programming languages. In this blog post, we’ve ventured into the realm of GO language, showcasing its application in the context of SAP S/4HANA Cloud APIs for backend development. We hope this exploration has also served as an inspiration for developers eager to expand their skill set. Embracing new languages not only enriches the development experience but also positions developers to tackle a broader array of challenges and contribute to innovative solutions in the ever-evolving landscape of enterprise application development.

I would like to express my heartfelt thanks to Jay Adnure  and Ryutaro Umezuki for their support in reviewing and providing valuable feedback for this blog post.

  1. SAP S/4HANA Cloud Documentation
  2. Go Documentation

文章来源: https://blogs.sap.com/2023/11/24/unleashing-the-potential-of-sap-s-4hana-cloud-for-asset-maintenance-with-go-language-for-seamless-extensibility/
如有侵权请联系:admin#unsafe.sh