Skip to content

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

Improve import

Gildas Garcia96474f8ac8a0
diff --git a/package-lock.json b/package-lock.json
index aec2f3a9..871f1c31 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -29,6 +29,7 @@
"@streamparser/json-whatwg": "^0.0.22",
"@tailwindcss/vite": "^4.1.11",
"@tanstack/react-query": "^5.90.12",
+ "@types/qs": "^6.14.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -40,8 +41,10 @@
"lodash": "^4.17.21",
"lucide-react": "^0.542.0",
"mime": "^4.1.0",
+ "ms": "^2.1.3",
"next-themes": "^0.4.6",
"papaparse": "^5.5.3",
+ "qs": "^6.14.1",
"query-string": "^7.1.3",
"ra-core": "^5.13.3",
"ra-data-fakerest": "^5.10.0",
@@ -70,6 +73,7 @@
"@types/faker": "^5.5.9",
"@types/jsonexport": "^3.0.5",
"@types/lodash": "^4.17.20",
+ "@types/ms": "^2.1.0",
"@types/node": "^22.16.5",
"@types/papaparse": "^5.3.16",
"@types/react": "^19.1.8",
@@ -4703,6 +4707,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "22.18.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.18.0.tgz",
@@ -4728,6 +4739,12 @@
"integrity": "sha512-PIzZZlEppgrpoT2QgbnDU+MMzuR6BbCjllj0bM70lWoejMeNJAxCchxnv7J3XFkI8MpygtRpzXrIlmWUBclP5A==",
"license": "MIT"
},
+ "node_modules/@types/qs": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz",
+ "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==",
+ "license": "MIT"
+ },
"node_modules/@types/react": {
"version": "19.1.12",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.12.tgz",
@@ -8575,7 +8592,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true,
"license": "MIT"
},
"node_modules/msw": {
@@ -9479,9 +9495,9 @@
}
},
"node_modules/qs": {
- "version": "6.14.0",
- "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
- "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
+ "version": "6.14.1",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
+ "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
diff --git a/package.json b/package.json
index 9b314136..4644eb7e 100644
--- a/package.json
+++ b/package.json
@@ -42,6 +42,7 @@
"@streamparser/json-whatwg": "^0.0.22",
"@tailwindcss/vite": "^4.1.11",
"@tanstack/react-query": "^5.90.12",
+ "@types/qs": "^6.14.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -53,8 +54,10 @@
"lodash": "^4.17.21",
"lucide-react": "^0.542.0",
"mime": "^4.1.0",
+ "ms": "^2.1.3",
"next-themes": "^0.4.6",
"papaparse": "^5.5.3",
+ "qs": "^6.14.1",
"query-string": "^7.1.3",
"ra-core": "^5.13.3",
"ra-data-fakerest": "^5.10.0",
@@ -83,6 +86,7 @@
"@types/faker": "^5.5.9",
"@types/jsonexport": "^3.0.5",
"@types/lodash": "^4.17.20",
+ "@types/ms": "^2.1.0",
"@types/node": "^22.16.5",
"@types/papaparse": "^5.3.16",
"@types/react": "^19.1.8",
diff --git a/scripts/supabase-remote-init.mjs b/scripts/supabase-remote-init.mjs
index 1f3ebb94..84513a07 100644
--- a/scripts/supabase-remote-init.mjs
+++ b/scripts/supabase-remote-init.mjs
@@ -139,6 +139,7 @@ async function setupDatabase({ databasePassword }) {
"push",
"--linked",
"--include-roles",
+ "--include-seed",
"--password",
databasePassword,
],
diff --git a/src/components/atomic-crm/layout/ImportFromJsonDialog.tsx b/src/components/atomic-crm/layout/ImportFromJsonDialog.tsx
index 0a8b0bdd..9423f5ce 100644
--- a/src/components/atomic-crm/layout/ImportFromJsonDialog.tsx
+++ b/src/components/atomic-crm/layout/ImportFromJsonDialog.tsx
@@ -1,4 +1,7 @@
+import React from "react";
+import { AlertCircleIcon } from "lucide-react";
import { Form, required } from "ra-core";
+import ms from "ms";
import {
Dialog,
DialogClose,
@@ -7,6 +10,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { FileField, FileInput } from "@/components/admin";
import {
@@ -14,9 +18,6 @@ import {
type ImportFromJsonStats,
useImportFromJson,
} from "./useImportFromJson";
-import React from "react";
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import { AlertCircleIcon } from "lucide-react";
export const ImportFromJsonDialog = (
props: React.ComponentProps<typeof Dialog>,
@@ -40,7 +41,8 @@ export const ImportFromJsonDialog = (
<AlertCircleIcon />
<AlertTitle>Unable to import this file.</AlertTitle>
<AlertDescription>
- {importStatus.error.message}
+ <p>{importStatus.error.message}</p>
+ <p>Duration: {ms(importStatus.duration, { long: true })}</p>
</AlertDescription>
<DownloadErrorFileButton
failedImports={importStatus.failedImports}
@@ -83,6 +85,7 @@ export const ImportFromJsonDialog = (
/>
</>
) : null}
+ <p>Duration: {ms(importStatus.duration, { long: true })}</p>
</AlertDescription>
</Alert>
)}
@@ -94,7 +97,7 @@ export const ImportFromJsonDialog = (
<DialogFooter>
<DialogClose asChild>
<Button variant="outline" type="button">
- Cancel
+ Close
</Button>
</DialogClose>
</DialogFooter>
diff --git a/src/components/atomic-crm/layout/useImportFromJson.ts b/src/components/atomic-crm/layout/useImportFromJson.ts
index 34a34a3e..bd112d3b 100644
--- a/src/components/atomic-crm/layout/useImportFromJson.ts
+++ b/src/components/atomic-crm/layout/useImportFromJson.ts
@@ -1,5 +1,10 @@
import { useState } from "react";
-import { type Identifier, useDataProvider, useEvent } from "ra-core";
+import {
+ type Identifier,
+ useDataProvider,
+ useEvent,
+ useRefresh,
+} from "ra-core";
import { JSONParser } from "@streamparser/json-whatwg";
import mime from "mime/lite";
import type { CrmDataProvider } from "../providers/types";
@@ -41,6 +46,7 @@ type ImportFromJsonErrorState = {
error: Error;
stats: ImportFromJsonStats;
failedImports: ImportFromJsonFailures;
+ duration: number;
};
type ImportFromJsonSuccessState = {
@@ -48,6 +54,7 @@ type ImportFromJsonSuccessState = {
stats: ImportFromJsonStats;
error: null;
failedImports: ImportFromJsonFailures;
+ duration: number;
};
type ImportFromJsonState =
@@ -76,6 +83,7 @@ const defaultStats = {
export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
const dataProvider = useDataProvider<CrmDataProvider>();
+ const refresh = useRefresh();
const [state, setState] = useState<ImportFromJsonState>({
status: "idle",
error: null,
@@ -84,6 +92,8 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
});
const importFile = useEvent(async (file: File) => {
+ const startedAt = new Date();
+
setState({
status: "importing",
stats: defaultStats,
@@ -113,7 +123,7 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
return existingRecord.data[0].id;
}
- const data = await dataProvider.salesCreate({
+ const { data } = await dataProvider.salesCreate({
email: dataToImport.email.trim(),
first_name: dataToImport.name.trim(),
last_name: dataToImport.name.trim(),
@@ -144,20 +154,22 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
};
const importContact = async (dataToImport: ContactImport) => {
- const tagsIds: Array<Identifier> = [];
+ let tagsIds: Array<Identifier> = [];
if (dataToImport.tags && Array.isArray(dataToImport.tags)) {
- for (const tag of dataToImport.tags) {
- if (idsMaps.tags[tag]) {
- tagsIds.push(idsMaps.tags[tag]);
- }
- const { data } = await dataProvider.create<Tag>("tags", {
- data: {
- name: tag,
- color: colors[Math.floor(Math.random() * colors.length)],
- },
- });
- tagsIds.push(data.id);
- }
+ tagsIds = await Promise.all(
+ dataToImport.tags.map(async (tag) => {
+ if (idsMaps.tags[tag]) {
+ return idsMaps.tags[tag];
+ }
+ const { data } = await dataProvider.create<Tag>("tags", {
+ data: {
+ name: tag,
+ color: colors[Math.floor(Math.random() * colors.length)],
+ },
+ });
+ return data.id;
+ }),
+ );
}
const { data } = await dataProvider.create("contacts", {
@@ -166,7 +178,7 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
first_name: dataToImport.firstName,
title: dataToImport.title,
background: dataToImport.background,
- linkedinUrl: dataToImport.linkedinUrl,
+ linkedin_url: dataToImport.linkedinUrl,
company_id: dataToImport.companyId
? idsMaps.companies[dataToImport.companyId]
: undefined,
@@ -246,13 +258,15 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
contact_id: idsMaps.contacts[dataToImport.contactId],
sales_id: idsMaps.sales[dataToImport.salesId] ?? defaultSale.id,
text: dataToImport.text,
- due_date: dataToImport.dueDate,
- done_date: dataToImport.doneDate,
+ due_date: dataToImport.dueDate || undefined,
+ done_date: dataToImport.doneDate || undefined,
},
});
};
+ let defaultSale: Sale | null = null;
const getDefaultSale = async () => {
+ if (defaultSale) return defaultSale;
const { data } = await dataProvider.getList<Sale>("sales", {
pagination: { page: 1, perPage: 1000 },
sort: { field: "id", order: "ASC" },
@@ -260,9 +274,11 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
});
// get the first admin or the first sale if no admin yet
- return data.find((item) => item.administrator) ?? data[0];
+ defaultSale = data.find((item) => item.administrator) ?? data[0];
+ return defaultSale;
};
+ let currentTask: Promise<any> | null = null;
let currentBatch: Array<Promise<void>> = [];
const BATCH_SIZE = 50;
@@ -276,25 +292,21 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
],
keepStack: false,
});
- const reader = file.stream().pipeThrough(parser).getReader();
-
+ const stream = file.stream();
+ const reader = stream.pipeThrough(parser).getReader();
+
+ const proccesBatchIfPossible = async (ignoreSize: boolean = false) => {
+ if (currentBatch.length === BATCH_SIZE || ignoreSize) {
+ currentTask = Promise.all(currentBatch);
+ await currentTask;
+ currentBatch = [];
+ currentTask = null;
+ }
+ };
while (true) {
- const proccesBatchIfPossible = async () => {
- if (currentBatch.length === BATCH_SIZE) {
- await Promise.all(currentBatch);
- currentBatch = [];
- }
- };
const { done, value: parsedElementInfo } = await reader.read();
if (done) {
- setState((old) => {
- if (old.status === "error") return old;
- return {
- ...old,
- status: "success",
- error: null,
- };
- });
+ await proccesBatchIfPossible(true);
break;
}
const { value, stack, partial } = parsedElementInfo;
@@ -340,13 +352,14 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
...old.failedImports,
sales: [...old.failedImports.sales, value],
},
+ duration: new Date().getDate() - startedAt.getDate(),
}));
}),
);
await proccesBatchIfPossible();
continue;
}
- await proccesBatchIfPossible();
+ await proccesBatchIfPossible(true);
// Error state should stop the import process
if (state.status === "error") {
await reader.cancel();
@@ -388,7 +401,7 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
await proccesBatchIfPossible();
continue;
}
- await proccesBatchIfPossible();
+ await proccesBatchIfPossible(true);
if (type === "contacts") {
if (!isContact(value)) continue;
@@ -423,7 +436,7 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
await proccesBatchIfPossible();
continue;
}
- await proccesBatchIfPossible();
+ await proccesBatchIfPossible(true);
if (type === "notes") {
if (!isNote(value)) continue;
@@ -456,7 +469,7 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
await proccesBatchIfPossible();
continue;
}
- await proccesBatchIfPossible();
+ await proccesBatchIfPossible(true);
if (type === "tasks") {
if (!isTask(value)) continue;
@@ -490,7 +503,7 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
continue;
}
- await proccesBatchIfPossible();
+ await proccesBatchIfPossible(true);
}
setState((old) => {
@@ -500,8 +513,10 @@ export const useImportFromJson = (): [ImportFromJsonState, ImportFunction] => {
return {
...old,
status: "success",
+ duration: new Date().getDate() - startedAt.getDate(),
};
});
+ refresh();
});
return [state, importFile];
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index e60a74a3..b0cff486 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -108,7 +108,7 @@ async function fetchAndUpdateCompanyData(
return { ...params, data: newData };
}
-const dataProviderWithCustomMethod: CrmDataProvider = {
+const dataProviderWithCustomMethod: DataProvider & Partial<CrmDataProvider> = {
...baseDataProvider,
unarchiveDeal: async (deal: Deal) => {
// get all deals where stage is the same as the deal to unarchive
@@ -158,17 +158,15 @@ const dataProviderWithCustomMethod: CrmDataProvider = {
password,
};
},
- salesCreate: async ({ ...data }: SalesFormData): Promise<Sale> => {
- const user = await dataProvider.create("sales", {
+ salesCreate: async ({ ...data }: SalesFormData): Promise<{ data: Sale }> => {
+ const response = await dataProvider.create("sales", {
data: {
...data,
password: "new_password",
},
});
- return {
- ...user.data,
- };
+ return response;
},
salesUpdate: async (
id: Identifier,
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index 406eab0d..07651575 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -1,15 +1,16 @@
-import { supabaseDataProvider } from "ra-supabase-core";
+import { supabaseDataProvider, supabaseHttpClient } from "ra-supabase-core";
import {
withLifecycleCallbacks,
- type CreateParams,
type DataProvider,
type GetListParams,
type Identifier,
- type UpdateParams,
+ type ResourceCallbacks,
} from "ra-core";
-
+import {
+ defaultPrimaryKeys,
+ defaultSchema,
+} from "@raphiniert/ra-data-postgrest";
import type {
- Contact,
ContactNote,
Deal,
DealNote,
@@ -19,8 +20,6 @@ import type {
SignUpData,
} from "../../types";
import { getActivityLog } from "../commons/activity";
-import { getCompanyAvatar } from "../commons/getCompanyAvatar";
-import { getContactAvatar } from "../commons/getContactAvatar";
import { getIsInitialized } from "./authProvider";
import { supabase } from "./supabase";
@@ -31,19 +30,25 @@ if (import.meta.env.VITE_SUPABASE_ANON_KEY === undefined) {
throw new Error("Please set the VITE_SUPABASE_ANON_KEY environment variable");
}
-const baseDataProvider = supabaseDataProvider({
+const config = {
instanceUrl: import.meta.env.VITE_SUPABASE_URL,
apiKey: import.meta.env.VITE_SUPABASE_ANON_KEY,
supabaseClient: supabase,
sortOrder: "asc,desc.nullslast" as any,
-});
+ primaryKeys: defaultPrimaryKeys,
+ httpClient: supabaseHttpClient({
+ apiKey: import.meta.env.VITE_SUPABASE_ANON_KEY,
+ supabaseClient: supabase,
+ }),
+ schema: defaultSchema,
+};
+
+const baseDataProvider = supabaseDataProvider(config);
const processCompanyLogo = async (params: any) => {
- let logo = params.data.logo;
+ const logo = params.data.logo;
- if (typeof logo !== "object" || logo === null || !logo.src) {
- logo = await getCompanyAvatar(params.data);
- } else if (logo.rawFile instanceof File) {
+ if (logo?.rawFile instanceof File) {
await uploadToBucket(logo);
}
@@ -56,29 +61,6 @@ const processCompanyLogo = async (params: any) => {
};
};
-async function processContactAvatar(
- params: UpdateParams<Contact>,
-): Promise<UpdateParams<Contact>>;
-
-async function processContactAvatar(
- params: CreateParams<Contact>,
-): Promise<CreateParams<Contact>>;
-
-async function processContactAvatar(
- params: CreateParams<Contact> | UpdateParams<Contact>,
-): Promise<CreateParams<Contact> | UpdateParams<Contact>> {
- const { data } = params;
- if (data.avatar?.src || !data.email_jsonb || !data.email_jsonb.length) {
- return params;
- }
- const avatarUrl = await getContactAvatar(data);
-
- // Clone the data and modify the clone
- const newData = { ...data, avatar: { src: avatarUrl || undefined } };
-
- return { ...params, data: newData };
-}
-
const dataProviderWithCustomMethods = {
...baseDataProvider,
async getList(resource: string, params: GetListParams) {
@@ -129,10 +111,13 @@ const dataProviderWithCustomMethods = {
};
},
async salesCreate(body: SalesFormData) {
- const { data, error } = await supabase.functions.invoke<Sale>("users", {
- method: "POST",
- body,
- });
+ const { data, error } = await supabase.functions.invoke<{ data: Sale }>(
+ "users",
+ {
+ method: "POST",
+ body,
+ },
+ );
if (!data || error) {
console.error("salesCreate.error", error);
@@ -235,100 +220,96 @@ const dataProviderWithCustomMethods = {
export type CrmDataProvider = typeof dataProviderWithCustomMethods;
-export const dataProvider = withLifecycleCallbacks(
- dataProviderWithCustomMethods,
- [
- {
- resource: "contactNotes",
- beforeSave: async (data: ContactNote, _, __) => {
- if (data.attachments) {
- for (const fi of data.attachments) {
- await uploadToBucket(fi);
- }
- }
- return data;
- },
+const lifeCycleCallbacks: ResourceCallbacks[] = [
+ {
+ resource: "contactNotes",
+ beforeSave: async (data: ContactNote, _, __) => {
+ if (data.attachments) {
+ data.attachments = await Promise.all(
+ data.attachments.map((fi) => uploadToBucket(fi)),
+ );
+ }
+ return data;
},
- {
- resource: "dealNotes",
- beforeSave: async (data: DealNote, _, __) => {
- if (data.attachments) {
- for (const fi of data.attachments) {
- await uploadToBucket(fi);
- }
- }
- return data;
- },
+ },
+ {
+ resource: "dealNotes",
+ beforeSave: async (data: DealNote, _, __) => {
+ if (data.attachments) {
+ data.attachments = await Promise.all(
+ data.attachments.map((fi) => uploadToBucket(fi)),
+ );
+ }
+ return data;
},
- {
- resource: "sales",
- beforeSave: async (data: Sale, _, __) => {
- if (data.avatar) {
- await uploadToBucket(data.avatar);
- }
- return data;
- },
+ },
+ {
+ resource: "sales",
+ beforeSave: async (data: Sale, _, __) => {
+ if (data.avatar) {
+ await uploadToBucket(data.avatar);
+ }
+ return data;
},
- {
- resource: "contacts",
- beforeCreate: async (params) => {
- return processContactAvatar(params);
- },
- beforeUpdate: async (params) => {
- return processContactAvatar(params);
- },
- beforeGetList: async (params) => {
- return applyFullTextSearch([
- "first_name",
- "last_name",
- "company_name",
- "title",
- "email",
- "phone",
- "background",
- ])(params);
- },
+ },
+ {
+ resource: "contacts",
+ beforeGetList: async (params) => {
+ return applyFullTextSearch([
+ "first_name",
+ "last_name",
+ "company_name",
+ "title",
+ "email",
+ "phone",
+ "background",
+ ])(params);
},
- {
- resource: "companies",
- beforeGetList: async (params) => {
- return applyFullTextSearch([
- "name",
- "phone_number",
- "website",
- "zipcode",
- "city",
- "stateAbbr",
- ])(params);
- },
- beforeCreate: async (params) => {
- const createParams = await processCompanyLogo(params);
-
- return {
- ...createParams,
- data: {
- ...createParams.data,
- created_at: new Date().toISOString(),
- },
- };
- },
- beforeUpdate: async (params) => {
- return await processCompanyLogo(params);
- },
+ },
+ {
+ resource: "companies",
+ beforeGetList: async (params) => {
+ return applyFullTextSearch([
+ "name",
+ "phone_number",
+ "website",
+ "zipcode",
+ "city",
+ "stateAbbr",
+ ])(params);
},
- {
- resource: "contacts_summary",
- beforeGetList: async (params) => {
- return applyFullTextSearch(["first_name", "last_name"])(params);
- },
+ beforeCreate: async (params) => {
+ const createParams = await processCompanyLogo(params);
+
+ return {
+ ...createParams,
+ data: {
+ ...createParams.data,
+ created_at: new Date().toISOString(),
+ },
+ };
},
- {
- resource: "deals",
- beforeGetList: async (params) => {
- return applyFullTextSearch(["name", "type", "description"])(params);
- },
+ beforeUpdate: async (params) => {
+ return await processCompanyLogo(params);
+ },
+ },
+ {
+ resource: "contacts_summary",
+ beforeGetList: async (params) => {
+ return applyFullTextSearch(["first_name", "last_name"])(params);
},
- ],
+ },
+ {
+ resource: "deals",
+ beforeGetList: async (params) => {
+ return applyFullTextSearch(["name", "type", "description"])(params);
+ },
+ },
+];
+
+export const dataProvider = withLifecycleCallbacks(
+ dataProviderWithCustomMethods,
+ lifeCycleCallbacks,
);
const applyFullTextSearch = (columns: string[]) => (params: GetListParams) => {
@@ -370,15 +351,32 @@ const uploadToBucket = async (fi: RAFile) => {
.createSignedUrl(fi.path, 60);
if (!error) {
- return;
+ return fi;
}
}
}
const dataContent = fi.src
- ? await fetch(fi.src).then((res) => res.blob())
+ ? await fetch(fi.src, {
+ mode: "no-cors",
+ })
+ .then((res) => {
+ if (res.status !== 200) {
+ return null;
+ }
+ return res.blob();
+ })
+ .catch(() => null)
: fi.rawFile;
+ if (dataContent == null) {
+ // We weren't able to download the file from its src (e.g. user must be signed in on another website to access it)
+ // or the file has no content (not probable)
+ // In that case, just return it as is: when trying to download it, users should be redirected to the other website
+ // and see they need to be signed in. It will then be their responsibility to upload the file back to the note.
+ return fi;
+ }
+
const file = fi.rawFile;
const fileExt = file.name.split(".").pop();
const fileName = `${Math.random()}.${fileExt}`;
diff --git a/supabase/migrations/20260107140209_contact_avatar.sql b/supabase/migrations/20260107140209_contact_avatar.sql
new file mode 100644
index 00000000..941cd792
--- /dev/null
+++ b/supabase/migrations/20260107140209_contact_avatar.sql
@@ -0,0 +1,165 @@
+create extension if not exists "http" with schema "extensions";
+
+ create table "public"."favicons_excluded_domains" (
+ "id" bigint generated by default as identity not null,
+ "domain" text not null
+ );
+
+
+alter table "public"."favicons_excluded_domains" enable row level security;
+
+CREATE UNIQUE INDEX favicons_excluded_domains_pkey ON public.favicons_excluded_domains USING btree (id);
+
+alter table "public"."favicons_excluded_domains" add constraint "favicons_excluded_domains_pkey" PRIMARY KEY using index "favicons_excluded_domains_pkey";
+
+set check_function_bodies = off;
+
+CREATE OR REPLACE FUNCTION public.get_avatar_for_email(email text)
+ RETURNS text
+ LANGUAGE plpgsql
+AS $function$declare email_hash text;
+declare gravatar_url text;
+declare gravatar_status int8;
+declare email_domain text;
+declare favicon_url text;
+declare domain_status int8;
+
+begin
+ -- Try to fetch a gravatar image
+ email_hash = encode(digest(email, 'sha256'), 'hex');
+ gravatar_url = concat('https://www.gravatar.com/avatar/', email_hash, '?d=404');
+
+ select status from http_get(gravatar_url) into gravatar_status;
+
+ if gravatar_status = 200 then
+ return gravatar_url;
+ end if;
+
+ -- Fallback to email's domain favicon if not excluded
+ email_domain = split_part(email, '@', 2);
+ return get_domain_favicon(email_domain);
+exception
+ when others then
+ return 'ERROR';
+end;$function$
+;
+
+CREATE OR REPLACE FUNCTION public.get_domain_favicon(domain_name text)
+ RETURNS text
+ LANGUAGE plpgsql
+AS $function$declare domain_status int8;
+
+begin
+ if exists (select from favicons_excluded_domains as fav where fav.domain = domain_name) then
+ return null;
+ end if;
+
+ return concat(
+ 'https://favicon.show/',
+ (regexp_matches(domain_name, '^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/?\n]+)', 'i'))[1]
+ );
+end;$function$
+;
+
+CREATE OR REPLACE FUNCTION public.handle_contact_saved()
+ RETURNS trigger
+ LANGUAGE plpgsql
+AS $function$declare contact_avatar text;
+declare emails_length int8;
+declare email_entry jsonb;
+
+begin
+ if new.avatar is not null then
+ return new;
+ end if;
+
+ select coalesce(jsonb_array_length(new.email_jsonb), 0) into emails_length;
+
+ if emails_length = 0 then
+ return new;
+ end if;
+
+ for email_entry in select jsonb_array_elements(new.email_jsonb)
+ loop
+ contact_avatar = get_avatar_for_email(email_entry->>'email');
+ if (contact_avatar is not null) then
+ exit;
+ end if;
+ end loop;
+
+ if contact_avatar is null then
+ return new;
+ end if;
+
+ new.avatar = concat('{"src":"', contact_avatar, '"}');
+ return new;
+end;$function$
+;
+
+grant delete on table "public"."favicons_excluded_domains" to "anon";
+
+grant insert on table "public"."favicons_excluded_domains" to "anon";
+
+grant references on table "public"."favicons_excluded_domains" to "anon";
+
+grant select on table "public"."favicons_excluded_domains" to "anon";
+
+grant trigger on table "public"."favicons_excluded_domains" to "anon";
+
+grant truncate on table "public"."favicons_excluded_domains" to "anon";
+
+grant update on table "public"."favicons_excluded_domains" to "anon";
+
+grant delete on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant insert on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant references on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant select on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant trigger on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant truncate on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant update on table "public"."favicons_excluded_domains" to "authenticated";
+
+grant delete on table "public"."favicons_excluded_domains" to "postgres";
+
+grant insert on table "public"."favicons_excluded_domains" to "postgres";
+
+grant references on table "public"."favicons_excluded_domains" to "postgres";
+
+grant select on table "public"."favicons_excluded_domains" to "postgres";
+
+grant trigger on table "public"."favicons_excluded_domains" to "postgres";
+
+grant truncate on table "public"."favicons_excluded_domains" to "postgres";
+
+grant update on table "public"."favicons_excluded_domains" to "postgres";
+
+grant delete on table "public"."favicons_excluded_domains" to "service_role";
+
+grant insert on table "public"."favicons_excluded_domains" to "service_role";
+
+grant references on table "public"."favicons_excluded_domains" to "service_role";
+
+grant select on table "public"."favicons_excluded_domains" to "service_role";
+
+grant trigger on table "public"."favicons_excluded_domains" to "service_role";
+
+grant truncate on table "public"."favicons_excluded_domains" to "service_role";
+
+grant update on table "public"."favicons_excluded_domains" to "service_role";
+
+
+ create policy "Enable access for authenticated users only"
+ on "public"."favicons_excluded_domains"
+ as permissive
+ for all
+ to authenticated
+using (true)
+with check (true);
+
+
+CREATE TRIGGER contact_saved BEFORE INSERT OR UPDATE ON public.contacts FOR EACH ROW EXECUTE FUNCTION public.handle_contact_saved();
diff --git a/supabase/migrations/20260107151133_company_avatar.sql b/supabase/migrations/20260107151133_company_avatar.sql
new file mode 100644
index 00000000..4f4381a7
--- /dev/null
+++ b/supabase/migrations/20260107151133_company_avatar.sql
@@ -0,0 +1,25 @@
+set check_function_bodies = off;
+
+CREATE OR REPLACE FUNCTION public.handle_company_saved()
+ RETURNS trigger
+ LANGUAGE plpgsql
+AS $function$declare company_logo text;
+
+begin
+ if new.logo is not null then
+ return new;
+ end if;
+
+ company_logo = get_domain_favicon(new.website);
+ if company_logo is null then
+ return new;
+ end if;
+
+ new.logo = concat('{"src":"', company_logo, '","title":"Company favicon"}');
+ return new;
+end;$function$
+;
+
+CREATE TRIGGER company_saved BEFORE INSERT OR UPDATE ON public.companies FOR EACH ROW EXECUTE FUNCTION public.handle_company_saved();
+
+
diff --git a/supabase/migrations/20260108100629_task_due_date_nullable.sql b/supabase/migrations/20260108100629_task_due_date_nullable.sql
new file mode 100644
index 00000000..f9e8c0e1
--- /dev/null
+++ b/supabase/migrations/20260108100629_task_due_date_nullable.sql
@@ -0,0 +1,3 @@
+alter table "public"."tasks" alter column "due_date" drop not null;
+
+
diff --git a/supabase/seed.sql b/supabase/seed.sql
index e69de29b..87b8fa99 100644
--- a/supabase/seed.sql
+++ b/supabase/seed.sql
@@ -0,0 +1,103 @@
+INSERT INTO favicons_excluded_domains (domain) VALUES
+ ('gmail.com'),
+ ('yahoo.com'),
+ ('hotmail.com'),
+ ('aol.com'),
+ ('hotmail.co.uk'),
+ ('hotmail.fr'),
+ ('msn.com'),
+ ('yahoo.fr'),
+ ('wanadoo.fr'),
+ ('orange.fr'),
+ ('comcast.net'),
+ ('yahoo.co.uk'),
+ ('yahoo.com.br'),
+ ('yahoo.co.in'),
+ ('live.com'),
+ ('rediffmail.com'),
+ ('free.fr'),
+ ('gmx.de'),
+ ('web.de'),
+ ('yandex.ru'),
+ ('ymail.com'),
+ ('libero.it'),
+ ('outlook.com'),
+ ('uol.com.br'),
+ ('bol.com.br'),
+ ('mail.ru'),
+ ('cox.net'),
+ ('hotmail.it'),
+ ('sbcglobal.net'),
+ ('sfr.fr'),
+ ('live.fr'),
+ ('verizon.net'),
+ ('live.co.uk'),
+ ('googlemail.com'),
+ ('yahoo.es'),
+ ('ig.com.br'),
+ ('live.nl'),
+ ('bigpond.com'),
+ ('terra.com.br'),
+ ('yahoo.it'),
+ ('neuf.fr'),
+ ('yahoo.de'),
+ ('alice.it'),
+ ('rocketmail.com'),
+ ('att.net'),
+ ('laposte.net'),
+ ('facebook.com'),
+ ('bellsouth.net'),
+ ('yahoo.in'),
+ ('hotmail.es'),
+ ('charter.net'),
+ ('yahoo.ca'),
+ ('yahoo.com.au'),
+ ('rambler.ru'),
+ ('hotmail.de'),
+ ('tiscali.it'),
+ ('shaw.ca'),
+ ('yahoo.co.jp'),
+ ('sky.com'),
+ ('earthlink.net'),
+ ('optonline.net'),
+ ('freenet.de'),
+ ('t-online.de'),
+ ('aliceadsl.fr'),
+ ('virgilio.it'),
+ ('home.nl'),
+ ('qq.com'),
+ ('telenet.be'),
+ ('me.com'),
+ ('yahoo.com.ar'),
+ ('tiscali.co.uk'),
+ ('yahoo.com.mx'),
+ ('voila.fr'),
+ ('gmx.net'),
+ ('mail.com'),
+ ('planet.nl'),
+ ('tin.it'),
+ ('live.it'),
+ ('ntlworld.com'),
+ ('arcor.de'),
+ ('yahoo.co.id'),
+ ('frontiernet.net'),
+ ('hetnet.nl'),
+ ('live.com.au'),
+ ('yahoo.com.sg'),
+ ('zonnet.nl'),
+ ('club-internet.fr'),
+ ('juno.com'),
+ ('optusnet.com.au'),
+ ('blueyonder.co.uk'),
+ ('bluewin.ch'),
+ ('skynet.be'),
+ ('sympatico.ca'),
+ ('windstream.net'),
+ ('mac.com'),
+ ('centurytel.net'),
+ ('chello.nl'),
+ ('live.ca'),
+ ('aim.com'),
+ ('bigpond.net.au'),
+ ('online.de'),
+ ('apple.com');