0% found this document useful (0 votes)
40 views7 pages

Contract Document Information Extract and Store in Salesforce

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views7 pages

Contract Document Information Extract and Store in Salesforce

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Contract Upload Automation Using LWC and Google Vertex AI for

Salesforce Opportunity

Objective:

The goal is to build a Lightning Web Component (LWC) that allows


users to upload contract documents to a Salesforce Opportunity.
Once the document is uploaded, the system will send the file to Google
Vertex AI for document processing, extract key information
(Client Legal Company Name and Contract Final Amount), and store it
in Salesforce Opportunity custom fields.

Updated Project Overview:

1. User uploads a contract document via the LWC on the Opportunity


page.
2. The uploaded contract is sent to Google Vertex AI for processing.
3. Google Vertex AI extracts the Client Legal Company Name and
Contract Amount.
4. The extracted information is stored in the Opportunity custom fields.

Step-by-Step Implementation Guide:

Step 1: Set Up Salesforce

1. Navigate to Salesforce Setup.


2. Go to Object Manager and find the Opportunity object.
3. Create the following custom fields on the Opportunity object:
- Legal Company Name: Text Field (API Name:
Legal_Company_Name__c)
- Contract Amount: Currency Field (API Name: Contract_Amount__c)

Step 2: Create the Lightning Web Component (LWC)


Create an LWC to upload contract files and display the extracted
information.
2.1 LWC Markup (HTML) - File Upload and Display

<template>
<lightning-card title="Upload Contract">
<lightning-file-upload
label="Upload Contract File"
record-id={recordId}
accepted-formats={acceptedFormats}
onuploadfinished={handleUploadFinished}>
</lightning-file-upload>
<template if:true={isLoading}>
<lightning-spinner
alternative-text="Processing..."></lightning-spinner>
</template>
<template if:true={companyName}>
<p>Extracted Legal Company Name: {companyName}</p>
</template>
<template if:true={contractAmount}>
<p>Extracted Contract Amount: {contractAmount}</p>
</template>
</lightning-card>
</template>

2.2 LWC JavaScript - Handle File Upload and Processing

import { LightningElement, api, track } from 'lwc';


import processContract from
'@salesforce/apex/ContractFileProcessor.processContract';

export default class ContractFileUpload extends LightningElement {


@api recordId;
@track companyName = '';
@track contractAmount = '';
@track isLoading = false;
acceptedFormats = ['.pdf'];

handleUploadFinished(event) {
this.isLoading = true;

const uploadedFiles = event.detail.files;


const contentDocumentId = uploadedFiles[0].documentId;

// Call Apex to process the contract file


processContract({ contentDocumentId: contentDocumentId,
opportunityId: this.recordId })
.then(result => {
this.companyName = result.companyName;
this.contractAmount = result.contractAmount;
this.isLoading = false;
})
.catch(error => {
console.error('Error processing contract:', error);
this.isLoading = false;
});
}
}

Step 3: Apex Controller for Google Vertex AI Processing

This Apex controller will handle sending the uploaded file to Google
Vertex AI and update the Opportunity with the extracted data.

3.1 Apex Controller Code

public class ContractFileProcessor {


@AuraEnabled
public static Map<String, Object> processContract(String
contentDocumentId, String opportunityId) {
// Retrieve the uploaded file
ContentVersion contentVersion = [SELECT VersionData FROM
ContentVersion WHERE ContentDocumentId = :contentDocumentId
LIMIT 1];
Blob fileBlob = contentVersion.VersionData;

// Call Google Vertex AI using an external API (via a Cloud


Function or App Engine)
HttpRequest req = new HttpRequest();
req.setEndpoint('https://your-app-engine-url/extract-contract-
fields');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBodyAsBlob(fileBlob);

Http http = new Http();


HttpResponse res = http.send(req);

if (res.getStatusCode() == 200) {
// Parse the response from Google Vertex AI
Map<String, Object> result = (Map<String, Object>)
JSON.deserializeUntyped(res.getBody());

// Update the Opportunity with the extracted values


Opportunity opp = [SELECT Id FROM Opportunity WHERE Id
= :opportunityId];
opp.Legal_Company_Name__c = (String)
result.get('company_name');
opp.Contract_Amount__c = Decimal.valueOf((String)
result.get('contract_amount'));
update opp;

return result;
} else {
throw new CustomException('Error processing contract: ' +
res.getBody());
}
}
}

Step 4: Deploy and Test LWC

1. Use Salesforce CLI or Developer Console to deploy the LWC to your


Salesforce org.
2. After deployment, drag the LWC onto the Opportunity Record Page
layout using App Builder.
3. Test the file upload process by uploading a contract to an
Opportunity.
Step 5: Set Up Google Vertex AI

1. Create a new project in Google Cloud.


2. Enable Vertex AI API and Cloud Storage API.
3. Set up a Cloud Storage Bucket to store the uploaded files from
Salesforce.
4. Create a Custom Document Processor in Vertex AI for contract
analysis.
- Train the model to recognize and extract the fields Client Legal
Company Name and Contract Amount.

Step 6: Deploy Python Script to Google Cloud

Deploy the Python script (for Google Vertex AI integration) to Google


Cloud App Engine or Cloud Functions. The script will process the
uploaded contract using Vertex AI and return the extracted information
(legal company name, contract amount).

6.1 Python Script for Google Vertex AI

import os
from google.cloud import storage
from google.cloud import aiplatform

# Initialize Google Cloud clients


storage_client = storage.Client()
project_id = "your-gcp-project-id"
location = "us-central1"
endpoint = "your-vertex-endpoint-id"

# Initialize Vertex AI prediction client


prediction_client = aiplatform.PredictionServiceClient()

def upload_contract(file_path, bucket_name):


# Uploads contract file to Cloud Storage
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(os.path.basename(file_path))
blob.upload_from_filename(file_path)
return f"gs://{bucket_name}/{blob.name}"
def extract_contract_fields(file_path):
# Extracts legal company name and contract amount from the
contract using Vertex AI
# Upload file to Cloud Storage
gcs_path = upload_contract(file_path, 'contract-upload-bucket')

# Prepare the request payload


payload = {
'instances': [{
'content': gcs_path,
'mime_type': 'application/pdf'
}]
}

# Call Vertex AI
response = prediction_client.predict(

endpoint=f'projects/{project_id}/locations/{location}/endpoints/{endp
oint}',
instances=payload['instances']
)

company_name = ''
contract_amount = ''

# Extract the relevant fields from the response


for prediction in response.predictions:
company_name = prediction['company_name']
contract_amount = prediction['contract_amount']

return company_name, contract_amount

# Example usage:
if __name__ == "__main__":
file_path = "path_to_your_contract.pdf"
company_name, contract_amount =
extract_contract_fields(file_path)
print(f"Extracted Legal Company Name: {company_name}")
print(f"Extracted Contract Amount: {contract_amount}")
Conclusion

By completing this project, students will learn how to:


- Create and deploy a Lightning Web Component (LWC) for file upload.
- Integrate Google Vertex AI to extract information from uploaded
contracts.
- Use Apex to handle the data flow between Salesforce and Google
Vertex AI.
- Deploy and connect Python scripts to Google Cloud for document
processing.

This project provides hands-on experience in integrating Salesforce


with machine learning platforms like Google Vertex AI, automating
business processes in contract management for a software services
company.

You might also like