Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

mailgun function initial implementation

Jean-Baptiste Kaiserb38a689c002a
diff --git a/.gitignore b/.gitignore
index c0556361..be2e0f96 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,4 +25,6 @@ supabase/.branches
supabase/.temp
dist/
-.env
\ No newline at end of file
+.env
+
+deno.lock
\ No newline at end of file
diff --git a/makefile b/makefile
index 329916d7..6e615313 100644
--- a/makefile
+++ b/makefile
@@ -15,7 +15,7 @@ start-supabase-functions: ## start the supabase Functions watcher
start-app: ## start the app locally
npm run dev
-start: start-supabase start-supabase-functions start-app ## start the stack locally
+start: start-supabase start-app ## start the stack locally
stop-supabase: ## stop local supabase
npx supabase stop
diff --git a/supabase/functions/_shared/supabaseAdmin.ts b/supabase/functions/_shared/supabaseAdmin.ts
new file mode 100644
index 00000000..b758ed92
--- /dev/null
+++ b/supabase/functions/_shared/supabaseAdmin.ts
@@ -0,0 +1,12 @@
+import { createClient, SupabaseClient } from 'jsr:@supabase/supabase-js@2';
+
+export const supabaseAdmin: SupabaseClient = createClient(
+ Deno.env.get('SUPABASE_URL') ?? '',
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
+ {
+ auth: {
+ autoRefreshToken: false,
+ persistSession: false,
+ },
+ }
+);
diff --git a/supabase/functions/mailgun/index.ts b/supabase/functions/mailgun/index.ts
index 1ef3fa63..2c553c1f 100644
--- a/supabase/functions/mailgun/index.ts
+++ b/supabase/functions/mailgun/index.ts
@@ -4,27 +4,181 @@
// Setup type definitions for built-in Supabase Runtime APIs
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';
-
-console.log('Hello from Functions!');
+import { supabaseAdmin } from '../_shared/supabaseAdmin.ts';
Deno.serve(async req => {
- const { name } = await req.json();
- const data = {
- message: `Hello ${name}!`,
- };
-
- return new Response(JSON.stringify(data), {
- headers: { 'Content-Type': 'application/json' },
- });
-});
+ // Only allow POST requests
+ if (req.method !== 'POST') {
+ return new Response(null, { status: 405 });
+ }
+
+ const data = await req.formData();
+ const to = data.get('To');
+ if (!to) return new Response('Missing parameter: To', { status: 406 });
+ const from = data.get('from');
+ if (!from) return new Response('Missing parameter: from', { status: 406 });
+ const subject = data.get('subject');
+ if (!subject)
+ return new Response('Missing parameter: subject', { status: 406 });
+ const strippedText = data.get('stripped-text');
+ if (!strippedText)
+ return new Response('Missing parameter: stripped-text', {
+ status: 406,
+ });
+
+ const noteContent = getNoteContent(
+ subject.toString(),
+ strippedText.toString()
+ );
+
+ const { email: salesEmail } = extractMailContactData(from.toString());
+ if (!salesEmail)
+ return new Response(
+ `Could not extract sales email from From: ${from}`,
+ { status: 406 }
+ );
+ const { data: sales, error: fetchSalesError } = await supabaseAdmin
+ .from('sales')
+ .select('*')
+ .eq('email', salesEmail)
+ .maybeSingle();
+ if (fetchSalesError)
+ return new Response(
+ `Could not fetch sales from database, email: ${salesEmail}`,
+ { status: 500 }
+ );
+ if (!sales)
+ return new Response(
+ `Unable to find sales in database, email: ${salesEmail}`,
+ { status: 406 }
+ );
+
+ const { firstName, lastName, email, domain } = extractMailContactData(
+ to.toString()
+ );
+ if (!email)
+ return new Response(`Could not extract email from To: ${to}`, {
+ status: 406,
+ });
-/* To invoke locally:
+ const { data: existingContact, error: fetchContactError } =
+ await supabaseAdmin
+ .from('contacts')
+ .select('*')
+ .eq('email', email)
+ .maybeSingle();
+ if (fetchContactError)
+ return new Response(
+ `Could not fetch contact from database, email: ${email}`,
+ { status: 500 }
+ );
+
+ // deno-lint-ignore no-explicit-any
+ let contact: any = undefined;
+ if (existingContact) {
+ contact = existingContact;
+ } else {
+ // If the contact does not exist, we need to create it, along with the company if needed
+ const { data: existingCompany, error: fetchCompanyError } =
+ await supabaseAdmin
+ .from('companies')
+ .select('*')
+ .eq('name', domain)
+ .maybeSingle();
+ if (fetchCompanyError)
+ return new Response(
+ `Could not fetch companies from database, name: ${domain}`,
+ { status: 500 }
+ );
+
+ // deno-lint-ignore no-explicit-any
+ let company: any = undefined;
+ if (existingCompany) {
+ company = existingCompany;
+ } else {
+ const { data: newCompanies, error: createCompanyError } =
+ await supabaseAdmin
+ .from('companies')
+ .insert({ name: domain, sales_id: sales.id })
+ .select();
+ if (createCompanyError)
+ return new Response(
+ `Could not create company in database, name: ${domain}`,
+ { status: 500 }
+ );
+ company = newCompanies[0];
+ }
+
+ // Create the contact
+ const { data: newContacts, error: createContactError } =
+ await supabaseAdmin
+ .from('contacts')
+ .insert({
+ first_name: firstName,
+ last_name: lastName,
+ email,
+ company_id: company.id,
+ sales_id: sales.id,
+ first_seen: new Date(),
+ last_seen: new Date(),
+ tags: [],
+ })
+ .select();
+ if (createContactError || !newContacts[0])
+ return new Response(
+ `Could not create contact in database, email: ${email}`,
+ { status: 500 }
+ );
+ contact = newContacts[0];
+ }
+
+ // Add note to new contact
+ const { error: createNoteError } = await supabaseAdmin
+ .from('contactNotes')
+ .insert({
+ contact_id: contact.id,
+ text: noteContent,
+ sales_id: sales.id,
+ });
+ if (createNoteError)
+ return new Response(
+ `Could not add note to contact ${email}, sales ${salesEmail}`,
+ { status: 500 }
+ );
+
+ return new Response('OK');
+});
- 1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
- 2. Make an HTTP request:
+/**
+ * Extracts the first name, last name, email, and domain from a mail contact (e.g. "To" or "From").
+ *
+ * Example:
+ * From: "Alice Cooper <[email protected]>"
+ *
+ * Return Value:
+ * {
+ * firstName: "Alice",
+ * lastName: "Cooper",
+ * email: "[email protected]",
+ * domain: "sandbox.mailgun.org"
+ * }
+ *
+ * @param to
+ * @returns
+ */
+const extractMailContactData = (to: string) => {
+ const [_match, fullName, email, domain] =
+ /([^<>]+)\s<([^\s<>]+@([^\s<>]+))>/.exec(to) || [];
+ let firstName = '';
+ let lastName = fullName;
+ if (fullName && fullName.includes(' ')) {
+ const parts = fullName.split(' ');
+ firstName = parts[0];
+ lastName = parts.slice(1).join(' ');
+ }
+ return { firstName, lastName, email, domain };
+};
- curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/mailgun' \
- --header 'Content-Type: application/json' \
- --data '{"name":"Functions"}'
+const getNoteContent = (subject: string, strippedText: string) => `${subject}
-*/
+${strippedText}`;
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 958370ac..6d3cfc29 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -1,5 +1,6 @@
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';
import { createClient } from 'jsr:@supabase/supabase-js@2';
+import { supabaseAdmin } from '../_shared/supabaseAdmin.ts';
export const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -8,17 +9,6 @@ export const corsHeaders = {
'Access-Control-Allow-Methods': 'POST, PATCH, DELETE',
};
-const supabaseServiceClient = createClient(
- Deno.env.get('SUPABASE_URL') ?? '',
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
- {
- auth: {
- autoRefreshToken: false,
- persistSession: false,
- },
- }
-);
-
function createErrorResponse(status: number, message: string) {
return new Response(JSON.stringify({ status, message }), {
headers: { 'Content-Type': 'application/json', ...corsHeaders },
@@ -27,7 +17,7 @@ function createErrorResponse(status: number, message: string) {
}
async function updateSaleDisabled(user_id: string, disabled: boolean) {
- return await supabaseServiceClient
+ return await supabaseAdmin
.from('sales')
.update({ disabled: disabled ?? false })
.eq('user_id', user_id);
@@ -37,7 +27,7 @@ async function updateSaleAdministrator(
user_id: string,
administrator: boolean
) {
- const { data: sales, error: salesError } = await supabaseServiceClient
+ const { data: sales, error: salesError } = await supabaseAdmin
.from('sales')
.update({ administrator })
.eq('user_id', user_id)
@@ -55,7 +45,7 @@ async function inviteUser(req: Request) {
await req.json();
const { data, error: userError } =
- await supabaseServiceClient.auth.admin.createUser({
+ await supabaseAdmin.auth.admin.createUser({
email,
password,
email_confirm: true,
@@ -88,7 +78,7 @@ async function inviteUser(req: Request) {
async function patchUser(req: Request) {
const { sales_id, email, first_name, last_name, administrator, disabled } =
await req.json();
- const { data: sale } = await supabaseServiceClient
+ const { data: sale } = await supabaseAdmin
.from('sales')
.select('*')
.eq('id', sales_id)
@@ -99,7 +89,7 @@ async function patchUser(req: Request) {
}
const { data, error: userError } =
- await supabaseServiceClient.auth.admin.updateUserById(sale.user_id, {
+ await supabaseAdmin.auth.admin.updateUserById(sale.user_id, {
email,
ban_duration: disabled ? '87600h' : 'none',
user_metadata: { first_name, last_name },