Building an intelligent CRM using ChatGPT, PostgreSQL, and ToolJet
Tags: webdev, javascript, chatgpt, lowcode
Published: 2023-05-22 09:48:05


> In this tutorial, you'll learn how to build a CRM (Customer Relationship Management) application using ChatGPT, ToolJet, and PostgreSQL.

## Introduction

The CRM application will allow you to add new users or customers to a PostgreSQL database, view their details on a dashboard, generate email templates using ChatGPT, and send them emails via [Sendinblue](https://www.sendinblue.com/).

We'll use ToolJet for the application interface in this tutorial.

## What is ToolJet?

[ToolJet](https://github.com/ToolJet/ToolJet) is an open-source low-code framework that enables us to build full-stack web applications within a few minutes. With ToolJet, you can create standalone fully-functional full-stack applications or embed applications into other websites.

ToolJet allows you to build applications that use relational and non-relational databases, REST APIs, OpenAI technologies, and cloud storage like [Google Cloud Storage](https://cloud.google.com/storage), [AWS S3](https://aws.amazon.com/pm/serv-s3), and [Minio](https://min.io/). It is an excellent development tool helping individuals, developers, and businesses create and ship products faster.

**Before we continue, I need your help? 😔**
I would be super happy if you could give us a star! And let me also know in the comments section. ❤️

[https://github.com/ToolJet/ToolJet](https://github.com/ToolJet/ToolJet)

![https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjlhNzRjMWJlYzgyNWZjYjcyOGMxYjJiYjQxOTQzYTU1NTg5YzAzNiZjdD1n/dfbMVqwq8GrC19xSEF/giphy.gif](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjlhNzRjMWJlYzgyNWZjYjcyOGMxYjJiYjQxOTQzYTU1NTg5YzAzNiZjdD1n/dfbMVqwq8GrC19xSEF/giphy.gif)

## Setting up an ElephantSQL (PostgreSQL) database

[ElephantSQL](https://www.elephantsql.com/) enables us to create a PostgreSQL database on the cloud instead of your local machine. Follow the steps below to create a PostgreSQL database:

Create an ElephantSQL account [here](https://customer.elephantsql.com/login).

Add a new database instance. No credit card or billing information is required.

Once you've created the database instance, your database information is displayed.


![01](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/272zsmojx8da1ma9jvto.png)

Congratulations! You've successfully created the database needed for this application. Next, let's build the application interface and connect the database to the application.

## Building the application with ToolJet

Here, you'll learn how to create a ToolJet account and build a fully functional application with ToolJet.

If you are new to ToolJet, [create an account](https://app.tooljet.com/signup).

Create a Workspace and a new app called CRM application.

![02-tooljet-workspace.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yyhdhr2vw98tg2j53qj7.png)

Build a user interface similar to the image below.

![03-app-preview.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxsffw7uiwti3en9f3ug.png)

To create the UI image above, you will first add a large container on the canvas that will house all the other UI elements of the application. Next, add the three container elements at the top of the page, the Add Lead button component and the Table component.

> ToolJet enables you to create applications' interfaces by dragging and dropping various UI components on the canvas.
> 

After recreating the UI, add an Action button with the text "Send Email" to the table. (We'll configure it later to enable us to email each user).

![04-action-buttons.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3ljnv3ovc22tvrfvhns.png)

To complete the UI, we need an interface that allows us to add a user to the database and another for editing and generating the email content for each user.

To do this, we'll use the [Modal component](https://docs.tooljet.com/docs/widgets/modal). We'll display a modal when we click on the Add Lead button - for adding new data and the "Send Email" action button - for entering the email content for the user.

![05-app-overview.gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58ku941i3dk3ha6eseh3.gif)

### The “Add New Lead” Modal

To display the Add New Lead Modal component, you need to create the modal and add an onClick event to the "Add Lead" button to show the modal.

![06-show-modal.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xrecm4bk2ojncpkqw3c5.png)

Add the following components to the modal, and remember to close the modal when you click the modal button.

![07-addnewlead-modal.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipm03cis8g9sqfy344j2.png)

### The “Send Email” modal

The Send Email modal allows us to enter the user's email, email subject, and content. You can also generate email content using the ChatGPT API. You'll learn how to do that in the upcoming sessions.

![08-sendEmail-modal.gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xgaylavyjun43j2vvczm.gif)

The toggle switch has an `onChange` event that hides the ChatGPT prompt input field and button whenever you don't need it.

![09-toggle-switch.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ed9ahpchfsmbbt1lsyx9.png)

Remember to close the modal when a user clicks the `Send Email` button.

Congratulations!🎉 You've completed building the UI for this application. In the upcoming sessions, you'll learn how to connect the user interface to a PostgreSQL database, communicate with [ChatGPT](https://platform.openai.com), and send emails using [Sendinblue](https://www.sendinblue.com).

## How to communicate with a PostgreSQL database in ToolJet

ToolJet allows us to communicate with external resources or create custom functions via a panel known as [Query Panel](https://docs.tooljet.com/docs/app-builder/query-panel). In ToolJet, any function that interacts with a database, API, or cloud storage and runs a JavaScript or Python code is called a Query.

![10-query-panel.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0mpk0c9lwiqt4jx45o2o.png)

Here, you'll learn how to communicate with a PostgreSQL database in ToolJet. First, let me walk you through connecting a PostgreSQL database to ToolJet.

### Connecting a PostgreSQL database to ToolJet

Select PostgreSQL from the list of databases under the Global Datasources panel, and provide the required information as shown below.

![11-add-postgres.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/664hgiq624ad21dkkunf.png)

From the image above, the host is the same as the server name on ElephantSQL (excluding the brackets). The username and database name are the same, and copy and paste the password into its field.

![12-connect-elephantSQL.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvrrd2g3dc0wakzrpkp0.png)

Scroll down the page and click `Test Connection`.

![13-test-connection.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tz0p08ohre5gl02ovdq6.png)

If the connection is verified, we can start making queries to the database.

![14-connection-verified.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdklu8d2slcwc5efs6sy.png)

### Querying a PostgreSQL database in ToolJet

Here, you'll learn how to query data from the database and display them accordingly within the application.

Before we begin, let's add some data to the database. Click PostgreSQL on the Query Panel, select SQL mode, and run the code snippet below to create a new table containing the data below.

```sql
CREATE TABLE Users (Name varchar(255), Email varchar(255), Phone varchar(255), Organisation varchar(255), Designation varchar(255), Status varchar(255));
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('Teja', 'teja@gmail.com', '+555-34569', 'ToolJet', 'Developer Advocate', 'Customer');
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('Badri', 'badri@gmail.com', '+555-59659', 'ToolJet', 'Engineering Manager', 'Prospect');
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('Jack', 'jack@gmail.com', '+555-44449', 'ToolJet', 'Software Engineer', 'Lead');
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('Nora', 'nora@gmail.com', '+555-46249', 'ToolJet', 'Product Manager', 'Customer');
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('Emily', 'emily@gmail.com', '+555-47893', 'ToolJet', 'Product Designer', 'Prospect');
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('Dave', 'dave@gmail.com', '+555-49313', 'ToolJet', 'Data analyst', 'Lead');
SELECT * FROM Users;
```

![15-add-data.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4dh6d064s6cl9dfl7ej.png)

You can view the data on ElephantSQL once it has been uploaded.

![16-view-data.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2t17ppq1t2tcjswba0gj.png)

Next, rename the query to `getTableData`, update the SQL editor to display all the table contents, and save the query.

![17-rename-query.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dx1k68qvppa4m038jhwk.png)

Update the Table component to display the data retrieved from the `getTableData` query.

![18-displayTable-data.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tny1jrfuf24zncb2bpzp.png)

Since we've displayed the contents on the table. Next, let's show the number of Customers, Leads, and Prospects available on the database.

Create three new queries based on the PostgreSQL database called `getLeadsCount`, `getProspectsCount`, and `getCustomersCount`.

Update the SQL editor for each query to retrieve the number of data under each category as done below, and save them.

```sql
SELECT COUNT(*)
FROM Users
WHERE Status IN ('Lead');
/*-- change 'Lead' for leads, 'Prospect' for prospects, 'Customer' for customers. ---*/
```

![19-display-counts.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4s3eoizatiilzi1wopx5.png)

Display the number of data returned from each query by replacing the text content within the container as done below.

![20-getData-counts.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ug6uu7akdon95kas4auu.png)
```
{{queries.getProspectsCount.data[0].count}}

//(Use {{queries.getLeadsCount.data[0].count}} for leads and {{queries.getCustomersCount.data[0].count}} for customers)
```

Finally, switch on the "Run this query on application load?" toggle for the `getTableData` and the other three queries.

![21-run-app.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkxohslstg1dprl213g7.png)

Congratulations! You've learnt how to query and display the data received within the application. Next, I will walk you through adding new data to the database via the application interface.

### Adding new users to the database

Here, you'll learn how to accept that data from the modal and add the user's data to the database.

![22a-addNewUser.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpqc7ib88l68xc20n5b5.png)

Create a new query related to the PostgreSQL data source that accepts the values from the modal and sends an SQL query to add the data to the database.

![22-add-user.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llhizit4gvm8gxw7uv52.png)

Ensure that the code snippet below matches the components' names from the modal. Copy the code snippet below into the SQL editor panel and save the query.

```sql
INSERT INTO Users(name, email, phone, organisation, designation, status) VALUES('{{components.name.value}}', '{{components.email.value}}', '{{components.phone.value}}', '{{components.organisation.value}}', '{{components.designation.value}}', '{{components.status.value}}');
```

Finally, add an `onClick` event to the `Add Lead` button to run the query on button click.

![23-addNewUser.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awdjo4kiivm8ro2z38yo.png)

## How to communicate with ChatGPT in ToolJet

Here, you'll learn how to communicate with ChatGPT via OpenAI in ToolJet.

### Setting up an OpenAI account

Log in or create an OpenAI account [here](https://openai.com/product).

Click `Personal` on the navigation bar and select `View API keys` from the menu bar to create a new secret key.

![05-openai-dashboard.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ggxnieexrli2bpxp2in.png)

Generate a new API key and copy it somewhere on your computer. We'll use it in the upcoming section.

### Communicating with the OpenAI API in ToolJet

Under the Global Datasources tab on your dashboard, click Plugins, and select OpenAI. Then, paste your API key and organization ID into the input fields and test the connection. 

You can now access the OpenAI data source from the query panel.

> If you don’t have an organization ID, use “Personal”.
> 

![24-openai-connection.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0rqvh327achnh3mwhii.png)

Select OpenAI from the Query Panel and set its content to draft an email using ChatGPT.

```
Draft an email to {{components.recipient.value}} about {{components.chatgptprompt.value}}
```

Run the query when a user clicks the Ask button on the modal.

![26-run-chatgpt.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cllzbj9iv7ryzm4o0w6p.png)

Finally, to display a selected user's email automatically on the modal, set the default value of the recipient's email input to `{{components.table1.selectedRow.email}}`. This automatically sets its value to the email of the selected user.

![27-autochange-email.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kq813x6psxx3fe35jwau.png)

## How to send emails via the Sendinblue API in ToolJet

[Sendinblue](https://www.sendinblue.com/) is a digital marketing tool that provides Email, SMS, Facebook, Chat, and more, via one platform to help grow businesses by building stronger customer relationships.

In this section, you'll learn how to integrate and send emails via Sendinblue in ToolJet. First, you need to log in or [create a SendinBlue account](https://www.sendinblue.com/).

Select SMTP and API on your dashboard, generate an SMTP key, and copy it somewhere on your computer. You'll need it shortly.

![28-generate-smtp.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzhwyacxvnj0skxjhdv5.png)

Return to your ToolJet app, add a new SMTP data source, and fill in the required credentials. Your password is the generated SMTP key.

![29-smtp-datasource.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukhdscpvuvf4hxmgve31.png)

If successfully connected, it will display "Connection Verified". Then you can start sending emails.

![30-connect-verified.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/219asl8q2w4v36w7x3xj.png)

Next, create the query for sending the emails. Provide your email, name, the recipient's email, subject, and title components.

![31-smtp-config.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av3n0c9ehjkizprq18f5.png)

Finally, save the query and run it when the Send Email button on the modal is clicked.

![32-app-reveal.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zza3wsg0hrv641hvwlv6.png)

Here is a working demo of the application: [https://tooljet-stny.onrender.com/applications/7a8867e3-3cea-49e3-89e7-8da39038b875](https://tooljet-stny.onrender.com/applications/7a8867e3-3cea-49e3-89e7-8da39038b875)

You can also [download its JSON file](https://tooljet.com/) and import it into a ToolJet app, but you'll need to provide your Sendinblue credentials and OpenAI API key.

## Conclusion

So far, you've learnt how to

- add a PostgreSQL database to ToolJet
- send emails within a ToolJet application using Sendinblue,
- communicate with ChatGPT via OpenAI in ToolJet, and
- Build full-stack applications in a few minutes with ToolJet.

[ToolJet](https://github.com/ToolJet/ToolJet) is both an excellent development tool and open-source - meaning its code is readily available for everyone to modify and improve. It has a [large community of developers](https://tooljet.slack.com/ssb/redirect) and talented contributors constantly maintaining and improving the software. As a user, you can be sure of getting the best performance when you use ToolJet.

Are you interested in contributing to ToolJet? Feel free to check out our GitHub repo- [https://github.com/ToolJet/ToolJet](https://github.com/ToolJet/ToolJet) to contribute and raise issues about ToolJet.

Thank you for reading!