Salesforce ERP Integration for managing finance of manufacturing industry

decor
decor

Salesforce ERP Integration

Salesforce has been truly marveling while delivering its services to a variety of companies ranging from a small scale to a vast scale. Across this blog, we are talking about an elevator manufacturing company which are in general huge in terms of capital, assets, and manpower. The beauty of the Salesforce lies in smoothly handling the operations of such industries, not only internally but also empowers them to go beyond Salesforce and use Salesforce as a helping hand.

Business Requirement Assumption and Schema Design for Salesforce ERP Integration

Many manufacturing companies have been using SAP or another popular ERP for ages and may not dare to switch to a different system. Let me tell you the answer to why by below example. Let’s take a scenario of CEO (of Elevator Manufacturing Company) who liked the functionality offered by Salesforce and want to implement such a CRM for its company to boost customer relations. The company creates hundreds of invoices every hour and wants it in Salesforce too.

They also need an ERP for themselves and can’t only rely on a CRM to get there done. In that case, integrating Salesforce with SAP is the best choice. As the invoices can reflect in Salesforce in real-time as soon as they are created in SAP, this choice becomes most feasible to the CEO. Hence, Salesforce acts as a helping hand instead of monopolizing the resources.

Understanding the requirement
decor
decor

Understanding the Business flow using a flowchart for Salesforce ERP Integration

decor
decor

The above diagram describes a high-level flow of the complete requirement. We have already have discussed a high-level view of the requirement, now let’s discuss this in more detail. Data can choose to come through JSON or XML as we are using Rest API here. Oh! I know your next question, why rest API? The answer is the modern standards. Since Rest is lightweight, faster, easy, and flexible, we will be choosing this API over any other.

Let’s assume both parties agree for the transfer of data using JSON, but the condition may consist of both insertable and updatable data. Are you confused about what I mean by that? See, invoices can be altogether new or can be an old one with some modification. It is vital that we also capture changes to the invoices. Consider a scenario, an end customer had bought 5 elevators for this business apartment but due to a damaged piece wants to return one and further decided to adjust in 4 elevators itself, thereby canceling 1 elevator. In this case, an invoice must be modified to reflect the billing for 4 elevators, and such change should appear in Salesforce too. Hence, the JSON file may consist of both new invoices, where we will use insert operation and modification in invoices where we will use update operation. I think the diagram above would be easily understandable to you, how data flow from SAP through JSON to Salesforce and Salesforce processes it to the database. Now here, this diagram defines two kinds of databases, one for success records and another for failed records. It is necessary to have two kinds of databases to handle exception occurring during processing and send back error records to SAP for correction. An exception can be of many types, sometimes your relationships are not correct, or your email fields consists of junk, or your phone number has some alphabets in it, or you forgot to capture the name of the person on the invoice! Jokes apart, but using the error database, proper exception management can be done, and the response for success or error can be sent back to SAP. “Response JSON,” an arrow going from Salesforce to SAP in the diagram, defines such a response.

As you have a bit more idea about the requirement now, Can you tell me one thing? How can you relate a record between SAP and Salesforce? I mean to say if I want to search for a record in SAP and the same record in Salesforce, how can I do that? If you know it, hats off! If you scratching your head, the next section is for you! Let’s start reading it.

decor
decor

Salesforce ERP Integration. Creating Business Fields and Relationships

Invoice Number is the answer to the question! An invoice number can help us recognize a record in both systems. Salesforce can capture data in the format of objects and fields. Objects refer to tables and Fields refers to columns in SQL. So creating a simple invoice labeled object and an invoice number labeled custom field in Salesforce can suffice the answer.
As you know now, how to invoice number field is important for general uses. Similarly, there might be many other fields that may be required by the users of the application or the business in day to day usage. For all those columns, we can create custom fields on the invoice object. Many relevant fields can be a balance, item code, quantity, tax, or other for a general invoice. For the sake of this blog, let’s consider only 4 fields- invoice number, account number, amount, and quantity. Shocked to see Account number here! It’s an obvious thing that the invoice might be linked to some accounts in the system. Customers are generally recognized as accounts in finance and so we have a standard table named Account already built-in Salesforce to be used.
The next question which might be arising in your mind is, why are we creating API for an invoice if we don’t have an API for accounts? The thing is accounts may not be formed on a day to day basis; the company may have ten accounts a month or 100 accounts for a year. This elevator industry works with a single account for the long term as they get contracts from a construction site or a renovation site. This market is not like an online shopping store, which makes the lakhs of new customers weekly. But the invoices can be in quantity since they cover a lot of stuff like elevators, wires, engineer fees, cables, or any other electronic equipment and they could be required at multiple stages of the project even also daily until the elevators are installed completely.
Further maintenance invoices can also be created for service agents. So accounts in Salesforce can be adjusted by manual creation or a data loader. Accounts must exist before invoices and behave as the parent of an invoice. In the blog, we will be discussing invoices only considering accounts already exists in the system.

Creating the Schema for Salesforce ERP Integration

The side image shows the custom fields created on the invoice object. It’s effortless to create objects and fields in Salesforce. For creating object   setup Gear → object manager → new object (button) . For creating fields  setup → object manager→ click on existing object → navigate to fields and relationships → New (button) . If you are looking at the invoice table precisely, you may find many other fields then required ones also. We only required invoice number, account number, amount, and quantity but few standard and custom fields are also there. We have made a relationship of parent-child between account and invoice since every invoice should always be related to an account. For now, each account can have many invoices but each invoice can have only one account. Due to this relationship, we can derive values from the account into a field in the invoice. Such fields are called formula fields, obviously not only this, formula fields are used in a variety of stuff. This is how you create fields and objects and then further use them as per your needs.

  • Object manager menu items
  • Schema Builder

The side diagram shows the same relationship between the account and invoice in a graphical format. You can also view it in your org setup → Schema Builder.
We have created our schema and ready to start the data transfer. But wait for a second, don’t you think there should be an authorizing medium which can verify our identity and allow us permission to transfer data for security purposes? No waiting, let’s start reading that.

decor
decor

Connected App – Your Security Manager in Salesforce CRM ERP Integration

The connected app is no less than then a biometrics system installed in your workplace. You have to show your credentials, face, or fingerprint to a biometrics system to log in to the workplace. Similarly, you have to show your credentials to a connected app to move into the system and perform an activity.

Creating Connected App

Setup → app manager → new connected app (button).

Once you have created your connected app by going step by step as Salesforce ask you. You will be able to see something like this, which shows you consumer key and consumer secret. These are the usernames and passwords for connecting to this app and gain authorization from it. In the Selected OAuth Scopes, you can see that I had selected all the required permission I wanted during app creation.

  • App manager
decor
decor

Testing the Salesforce CRM ERP Integration using Postman

It’s time to test your connected app for authorization. You can use any tools available in the market, but we are using Postman here for the sake of simplicity and popularity. Download Postman from the official website and get started. An authorization API call will be sent to the Salesforce connected app, which should consist of various parameters. The format for such API calls is explained below.

METHOD: POST
URL: login.salesforce.com/services/oauth2/token
Note: Please use the above URL to retrieve Production authorization token only.

Set Parameters:
grant_type: password
Client id: *************************************************************************
client_secret: *******************
username: salesforce_username
password: salesforce_password + security_token

In real-time, SAP developer will create a code and execute it to hit our connected app and the below image shows how the same thing can be done in Postman. Just set all the parameters as displayed and hit the send button.

Once you click the Send button, some response will start appearing to you with 200 success code, if everything works well. Eventually, if it will show some 400 or 500 series error code and you have to resolve the issue to move ahead.

  • Postman screenshot without signs
decor
decor

Once above steps Return Success it will share the format like below
Success Response for Authorization Token: (JSON format)
{
“access_token”:
“***************************************************************************”,
“instance_url”: “https://demo-1322–Full.cs17.cloudforce.com”,
“id”: “https://test.salesforce.com/id/00Dg0000006Ts42EAC/0053700000IaVuAAK”,
“token_type”: “Bearer”,
“issued_at”: “1494935021675”,
“signature”: “qsTeghncfldJb6VLcnowKls/cre3mwN6BVBTHxh9sC8=”
}

decor

The side screen shows a successful response to authentication. We have hidden the username and password of the org for security purposes.
The access token and instance URL in success response will be required for further sending the data to SFDC and hence need to be preserved. Please store them somewhere with you and move to the next important section of the blog.

decor
decor

Creating a Web service – Real-time transfer of Invoices from SAP to SFDC

Developer at SAP end will develop a code that requests for authentication to the SFDC, and once such request is authenticated, an access token will be returned. Now using that token further request can be sent. We will continue the process of sending data to the latter part of this blog since it is important first to create a web service now. Because there is no point in sending data to SFDC without any web service, no one will be available to accept and process the payloads.

 

Note: The term payload or JSON request or API call belongs to the same meaning.

 

Building and understanding the web service class

 

Creating a web service class will help us to accept payloads and process them. Payloads are nothing but JSON format request sent by an external party to Salesforce. Such payloads can consist of authentication information or the data to be processed in the Salesforce. We will be discussing payloads format in the latter part but before that let’s create a web service class.

 

Algorithm for building the class:

 

  • – Host a URL for connection.
  • – Create a wrapper class for storing multiple invoices.
  • – Create a post method to accept payloads.
  • – Use wrapper array for iterating invoices.
  • – Identify the account in the system user account number.
  • – Identify the existence of the invoice using the invoice number.
  • – Create a new invoice if it doesn’t exist or append the values to an existing invoice if it exists.
  • – Send the error or success response.

 

The above algorithm might surely have given you clarity on how to proceed with the process. The more brief explanation ahead will help you grasp whichever step is not clear to you. We have created a sample web service class for you and attached that below for your reference

decor
decor

Understanding the code Snippet:

 

decor
decor

This code is not in the optimized state now and will require your expertise to fix many things before using it in real-time. But for the sake of understanding the logic, it is very well written.

We had used VS code to write out the class, but you can choose your desired IDEs or text editors. You always have to define a web service class by rest resource and the URL to hit using this statement. @RestResource(urlMapping=’/updateSapSdfcApi/*’)
Here updateSapSdfcApi is the URL of the web service where we will send our payload or JSON.

We will be receiving multiple invoices in the JSON file at the same time. To accommodate this, we have used Item class. Item class is a wrapper class and is capable of returning multiple invoices. You can rename this class as per your conventions since it’s a custom-built class. @HttpPost is the method that takes care of the insertion of incoming records into the system. Without @HttpPost, payload sent by SAP, will not hit the doPost method and this method will not be executed. And if this post doesn’t execute, no process will take place. Arguments in the doPost method accepts an array of invoices via Item class and are ready to be used automatically. Consider EMC have a truck full of elevators and he wants to apply a quality checked sticker on each elevator. Then, each elevator must be picked, processed, and then labeled. Similarly, Records array is the basket of invoices and we have to iterate over each record to process it. Such iteration can be done through a ‘for’ statement. Line 15 checks for the existing account and map it to the invoice. Line 16 checks if the invoice is new in the system or an existing one. Based on its existence, if and else has been defined. ‘If’ statement contains logic for new invoices creation and ‘else’ for existing ones. ‘Else’ uses shorthand operator to append the new values to the existing values. Let’s understand this with an example. There is an existing invoice in the system for ABC customer with 10k$ but it was found later that there was an issue and transportation cost was missed during invoice creation. The invoice was updated on the next day to reflect 1k$ more in the bill.
invObject.amount__c += i.amount; → This statement can sum up the existing 10k with new 1k and place 11k in the system. This statement is capable of handling negative corrections also.

Finally, the JSON response has been sent at last. There are many possible optimizations to the code above. We must not write a query in the ‘for’ loop. We should not do a DML statement inside a ‘for’ loop. All this can be fixed by used collections like maps and list properly. I leave it up to you for fixing the class issues and executing them. I hope you will have a lovely time playing with the code.

decor
decor

Format of the body of request or payload

As promised earlier, now it is the time to see how the payload looks. This is a JSON format only.

Body of Request: (JSON format for Single Record)Body of Request: (JSON format for multiple Records)
{
  "records": [{
                       "invoice_number": "inv001",
                       "account_number": "acc001",
                       "amount": 200000,
                       "quantity": 10
                     }
             ]
}
{
  "records": [{
                       "invoice_number": "inv001",
                       "account_number": "acc001",
                       "amount": 200000,
                       "quantity": 10
                     },
                     {
                       "invoice_number": "inv002",
                       "account_number": "acc002",
                       "amount": 300000,
                       "quantity": 15
                    }
             ]
}

Note: In the above example, only two records have been shown on the JSON for the sake of simplicity. Similarly, multiple records can be passed to Salesforce by adding records so on.

decor
decor

Testing the functionality

The process ahead resumes from where we left. Once your authentication is completed, access token has been received and web service class is also built, we can move ahead with the complete end to end functionality testing.

    Pick up the access_token and instance_url from the response received in 
    the success response for further use

    URL: <instance_url>/services/apexrest/updateSapSfdcApi
    Note: instance_url is nothing but URL you have received in Above Success Authorization. updateSapSfdcApi is the mapping used in first line of your code.
    Set Headers:
Label: Authorization
        • Value: Bearer <space><access_token>
          Example- Bearer 00Dg0000006Ts42!ARkAQHggwrcAkWhwel_1xrlKBgFX3mfX2lLuC8_4pM
    Note: access_token is nothing but URL you have received in previous Success Authorization.
Label: Content-Type
        • Value: application/json
decor
decor

Once Operation is completed Sfdc will return Success and Error Response Code

CodeTypeDescription
200Success
OtherError

Below figures will describe the actual placement of the above protocols in the Postman. The figures have been marked to describe my details; please go through it preciously. If you find any component being hidden or scratched, please apologize to us for it, as it was a sensitive matter.

decor
decor

Once you set your Postman similar to above, you are just a step away from successfully executing your application. You can have to click on the send button and see the magic! The below figures shows the actual output response in the Postman and the Salesforce both.

decor
decor

Hurray! You have completed the functionality. Now you can change your web service code as per your requirement and all other steps remain the same. For your reference we are attaching the code also, go ahead show your creativity!

decor
Error Response

Error Response

Headers of Error Response: (HTML format)
HTTP/1.1 400 Bad Request

Date: Fri, 22 May 2015 17:32:10 GMT
Set-Cookie: BrowserId=D_3feNw7RYmP4DA;Path=/;Domain=.salesforce.com;Expires=Tue, 21-Jul-2015 17:32:10 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked

 

Body of Error Response: (JSON format)

  [ {
    "errorCode" : "INVALID_ID_FIELD",
    "message" : "Invalid identifier: 0D5D0000000XZoHKAW"
  } ]
Note: the above values are only for testing purpose
Success Response
Web Service Code:
decor
decor

CRM ERP Integration Conclusion

With some hours of hard work, I believe you have successfully understood the concept. You should be appreciated for reaching until here and providing your time and efforts. It matters a lot to us that we were able to help you. Now the point is you have achieved a new credential in Salesforce and this privilege can help your company or you in mastering your business flow.
We have many new features and functionality waiting for you to be learned in the next coming blogs. If you like this blog, make sure to read the next one too, which is focussed on saving your company’s operations manual time for processing various bank files and payments. All the payment settlement can be done automatically in Salesforce against the bank files, which could reduce the operation staff and ultimately generate revenue for the company. See you there!

decor
decor
Need Help Migrating to Salesforce?
Send Message
Follow Us


3100 E 45th St,
Cleveland, OH
44127