Skip to content

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

Delete note attachments when deleting notes

Anibal Svarcasab173a932057
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.spec.ts b/src/components/atomic-crm/providers/supabase/dataProvider.spec.ts
new file mode 100644
index 00000000..c00146d0
--- /dev/null
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.spec.ts
@@ -0,0 +1,178 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockBaseGetList = vi.fn();
+const mockBaseGetOne = vi.fn();
+const mockBaseDelete = vi.fn();
+const mockBaseCreate = vi.fn();
+const mockBaseUpdate = vi.fn();
+const mockBaseGetMany = vi.fn();
+const mockBaseGetManyReference = vi.fn();
+const mockBaseUpdateMany = vi.fn();
+const mockBaseDeleteMany = vi.fn();
+
+const mockSupabaseDataProvider = vi.fn(() => ({
+ getList: mockBaseGetList,
+ getOne: mockBaseGetOne,
+ getMany: mockBaseGetMany,
+ getManyReference: mockBaseGetManyReference,
+ create: mockBaseCreate,
+ update: mockBaseUpdate,
+ updateMany: mockBaseUpdateMany,
+ delete: mockBaseDelete,
+ deleteMany: mockBaseDeleteMany,
+}));
+
+const mockStorageRemove = vi.fn();
+const mockStorageCreateSignedUrl = vi.fn();
+const mockStorageUpload = vi.fn();
+const mockStorageGetPublicUrl = vi.fn();
+
+const mockStorageFrom = vi.fn(() => ({
+ remove: mockStorageRemove,
+ createSignedUrl: mockStorageCreateSignedUrl,
+ upload: mockStorageUpload,
+ getPublicUrl: mockStorageGetPublicUrl,
+}));
+
+const mockSupabase = {
+ storage: {
+ from: mockStorageFrom,
+ },
+ auth: {
+ signUp: vi.fn(),
+ },
+ functions: {
+ invoke: vi.fn(),
+ },
+};
+
+const mockGetIsInitialized = vi.fn();
+(mockGetIsInitialized as any)._is_initialized_cache = false;
+
+vi.mock("ra-supabase-core", () => ({
+ supabaseDataProvider: mockSupabaseDataProvider,
+}));
+
+vi.mock("./supabase", () => ({
+ supabase: mockSupabase,
+}));
+
+vi.mock("./authProvider", () => ({
+ getIsInitialized: mockGetIsInitialized,
+}));
+
+vi.mock("../commons/activity", () => ({
+ getActivityLog: vi.fn(),
+}));
+
+describe("supabase dataProvider note attachment deletion", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+
+ Object.assign(import.meta.env, {
+ VITE_SUPABASE_URL: "http://127.0.0.1:54321",
+ VITE_SB_PUBLISHABLE_KEY: "test-key",
+ });
+
+ mockStorageRemove.mockResolvedValue({ error: null });
+ mockBaseDelete.mockResolvedValue({ data: { id: 1 } });
+ mockStorageGetPublicUrl.mockReturnValue({
+ data: {
+ publicUrl: "http://127.0.0.1:54321/storage/v1/object/public/attachments/file.txt",
+ },
+ });
+
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("deletes contact note attachment by path", async () => {
+ const { dataProvider } = await import("./dataProvider");
+ const previousData = {
+ id: 1,
+ attachments: [
+ {
+ title: "file.txt",
+ src: "http://127.0.0.1:54321/storage/v1/object/public/attachments/file.txt",
+ path: "file.txt",
+ },
+ ],
+ };
+
+ await dataProvider.delete("contact_notes", { id: 1, previousData } as any);
+
+ expect(mockStorageFrom).toHaveBeenCalledWith("attachments");
+ expect(mockStorageRemove).toHaveBeenCalledWith(["file.txt"]);
+ expect(mockBaseDelete).toHaveBeenCalledWith("contact_notes", {
+ id: 1,
+ previousData,
+ });
+ });
+
+ it("deletes deal note attachment using src when path is missing", async () => {
+ const { dataProvider } = await import("./dataProvider");
+ const attachmentSrc =
+ "http://127.0.0.1:54321/storage/v1/object/public/attachments/folder/my%20report.txt?download=1";
+ const previousData = {
+ id: 2,
+ attachments: [
+ {
+ title: "my report.txt",
+ src: attachmentSrc,
+ },
+ ],
+ };
+
+ await dataProvider.delete("deal_notes", { id: 2, previousData } as any);
+
+ expect(mockStorageRemove).toHaveBeenCalledWith([attachmentSrc]);
+ expect(mockBaseDelete).toHaveBeenCalledWith("deal_notes", {
+ id: 2,
+ previousData,
+ });
+ });
+
+ it("does not call storage remove when note has no attachments", async () => {
+ const { dataProvider } = await import("./dataProvider");
+ const previousData = {
+ id: 3,
+ attachments: [],
+ };
+
+ await dataProvider.delete("contact_notes", { id: 3, previousData } as any);
+
+ expect(mockStorageRemove).not.toHaveBeenCalled();
+ expect(mockBaseDelete).toHaveBeenCalledWith("contact_notes", {
+ id: 3,
+ previousData,
+ });
+ });
+
+ it("throws and aborts note deletion when storage removal fails", async () => {
+ const { dataProvider } = await import("./dataProvider");
+ const previousData = {
+ id: 4,
+ attachments: [
+ {
+ title: "fail.txt",
+ src: "http://127.0.0.1:54321/storage/v1/object/public/attachments/fail.txt",
+ path: "fail.txt",
+ },
+ ],
+ };
+
+ mockStorageRemove.mockResolvedValueOnce({
+ error: { message: "remove failed" },
+ });
+
+ await expect(
+ dataProvider.delete("contact_notes", { id: 4, previousData } as any),
+ ).rejects.toThrow("Failed to delete note attachments");
+
+ expect(mockBaseDelete).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index 98fae965..9f8b5bbc 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -19,6 +19,8 @@ import { getActivityLog } from "../commons/activity";
import { getIsInitialized } from "./authProvider";
import { supabase } from "./supabase";
+const ATTACHMENTS_BUCKET = "attachments";
+
if (import.meta.env.VITE_SUPABASE_URL === undefined) {
throw new Error("Please set the VITE_SUPABASE_URL environment variable");
}
@@ -51,6 +53,35 @@ const processCompanyLogo = async (params: any) => {
};
};
+const deleteNoteAttachments = async (
+ params: { id: Identifier; previousData?: ContactNote | DealNote },
+ dataProvider: DataProvider,
+ resource: string,
+) => {
+ const note =
+ params.previousData ??
+ (await dataProvider.getOne<ContactNote | DealNote>(resource, {
+ id: params.id,
+ })).data;
+
+ const paths = extractAttachmentPaths(note.attachments);
+
+ if (paths.length === 0) {
+ return params;
+ }
+
+ const { error } = await supabase.storage
+ .from(ATTACHMENTS_BUCKET)
+ .remove(paths);
+
+ if (error) {
+ console.error("deleteAttachmentsError", error);
+ throw new Error("Failed to delete note attachments");
+ }
+
+ return params;
+};
+
const dataProviderWithCustomMethods = {
...baseDataProvider,
async getList(resource: string, params: GetListParams) {
@@ -227,6 +258,8 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [
}
return data;
},
+ beforeDelete: async (params, dataProvider, resource) =>
+ deleteNoteAttachments(params, dataProvider, resource),
},
{
resource: "deal_notes",
@@ -238,6 +271,8 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [
}
return data;
},
+ beforeDelete: async (params, dataProvider, resource) =>
+ deleteNoteAttachments(params, dataProvider, resource),
},
{
resource: "sales",
@@ -338,12 +373,36 @@ const applyFullTextSearch = (columns: string[]) => (params: GetListParams) => {
};
};
+const extractAttachmentPaths = (attachments?: RAFile[] | null): string[] => {
+ const paths = attachments
+ ?.map((attachment) => extractAttachmentPath(attachment))
+ .filter((path): path is string => path != null && path.length > 0);
+
+ return paths ? Array.from(new Set(paths)) : [];
+};
+
+const extractAttachmentPath = (attachment?: Partial<RAFile> | null) => {
+ if (!attachment) {
+ return null;
+ }
+
+ if (attachment.path) {
+ return attachment.path;
+ }
+
+ if (!attachment.src) {
+ return null;
+ }
+
+ return attachment.src;
+};
+
const uploadToBucket = async (fi: RAFile) => {
if (!fi.src.startsWith("blob:") && !fi.src.startsWith("data:")) {
// Sign URL check if path exists in the bucket
if (fi.path) {
const { error } = await supabase.storage
- .from("attachments")
+ .from(ATTACHMENTS_BUCKET)
.createSignedUrl(fi.path, 60);
if (!error) {
@@ -377,7 +436,7 @@ const uploadToBucket = async (fi: RAFile) => {
const fileName = `${Math.random()}${fileExt}`;
const filePath = `${fileName}`;
const { error: uploadError } = await supabase.storage
- .from("attachments")
+ .from(ATTACHMENTS_BUCKET)
.upload(filePath, dataContent);
if (uploadError) {
@@ -385,7 +444,9 @@ const uploadToBucket = async (fi: RAFile) => {
throw new Error("Failed to upload attachment");
}
- const { data } = supabase.storage.from("attachments").getPublicUrl(filePath);
+ const { data } = supabase.storage
+ .from(ATTACHMENTS_BUCKET)
+ .getPublicUrl(filePath);
fi.path = filePath;
fi.src = data.publicUrl;