A full-featured CRM built with React, shadcn/ui, and Supabase.
Move note attachment cleanup out of Supabase dataProvider lifecycles
Anibal Svarcas8c0cce2f1624
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.spec.ts b/src/components/atomic-crm/providers/supabase/dataProvider.spec.tsindex fb023814..d4bcff8f 100644--- a/src/components/atomic-crm/providers/supabase/dataProvider.spec.ts+++ b/src/components/atomic-crm/providers/supabase/dataProvider.spec.ts@@ -65,7 +65,7 @@ vi.mock("../commons/activity", () => ({getActivityLog: vi.fn(),}));-describe("supabase dataProvider note attachment deletion", () => {+describe("supabase dataProvider note deletion", () => {beforeEach(() => {vi.resetModules();vi.clearAllMocks();@@ -91,7 +91,7 @@ describe("supabase dataProvider note attachment deletion", () => {vi.restoreAllMocks();});- it("deletes contact note attachment by path", async () => {+ it("delegates contact note deletion to base provider", async () => {const { dataProvider } = await import("./dataProvider");const previousData = {id: 1,@@ -106,15 +106,14 @@ describe("supabase dataProvider note attachment deletion", () => {await dataProvider.delete("contact_notes", { id: 1, previousData } as any);- expect(mockStorageFrom).toHaveBeenCalledWith("attachments");- expect(mockStorageRemove).toHaveBeenCalledWith(["file.txt"]);+ expect(mockStorageRemove).not.toHaveBeenCalled();expect(mockBaseDelete).toHaveBeenCalledWith("contact_notes", {id: 1,previousData,});});- it("deletes deal note attachment by extracting path from src", async () => {+ it("delegates deal note deletion to base provider", async () => {const { dataProvider } = await import("./dataProvider");const previousData = {id: 2,@@ -128,123 +127,10 @@ describe("supabase dataProvider note attachment deletion", () => {await dataProvider.delete("deal_notes", { id: 2, previousData } as any);- expect(mockStorageRemove).toHaveBeenCalledWith(["folder/my report.txt"]);+ expect(mockStorageRemove).not.toHaveBeenCalled();expect(mockBaseDelete).toHaveBeenCalledWith("deal_notes", {id: 2,previousData,});});-- it("deletes deal note attachment from a storage URL with another API version", async () => {- const { dataProvider } = await import("./dataProvider");- const previousData = {- id: 9,- attachments: [- {- title: "my report.txt",- src: "http://127.0.0.1:54321/storage/v2/object/public/attachments/folder/my%20report.txt?download=1",- },- ],- };-- await dataProvider.delete("deal_notes", { id: 9, previousData } as any);-- expect(mockStorageRemove).toHaveBeenCalledWith(["folder/my report.txt"]);- expect(mockBaseDelete).toHaveBeenCalledWith("deal_notes", {- id: 9,- previousData,- });- });-- it("fetches note when previousData is missing and deletes its attachments", async () => {- const { dataProvider } = await import("./dataProvider");- const fetchedNote = {- id: 5,- attachments: [- {- title: "from-fetch.txt",- src: "http://127.0.0.1:54321/storage/v1/object/public/attachments/from-fetch.txt",- path: "from-fetch.txt",- },- ],- };-- mockBaseGetOne.mockResolvedValueOnce({ data: fetchedNote });-- await dataProvider.delete("contact_notes", { id: 5 } as any);-- expect(mockBaseGetOne).toHaveBeenCalledWith("contact_notes", { id: 5 });- expect(mockStorageRemove).toHaveBeenCalledWith(["from-fetch.txt"]);- expect(mockBaseDelete).toHaveBeenCalledWith("contact_notes", { id: 5 });- });-- it("deduplicates attachment paths before calling storage remove", async () => {- const { dataProvider } = await import("./dataProvider");- const duplicatePath =- "http://127.0.0.1:54321/storage/v1/object/public/attachments/folder/my%20report.txt?download=1";- const previousData = {- id: 8,- attachments: [- {- title: "duplicate-1.txt",- src: duplicatePath,- path: "dup.txt",- },- {- title: "duplicate-2.txt",- src: duplicatePath,- path: "dup.txt",- },- ],- };-- await dataProvider.delete("contact_notes", { id: 8, previousData } as any);-- expect(mockStorageRemove).toHaveBeenCalledTimes(1);- expect(mockStorageRemove).toHaveBeenCalledWith(["dup.txt"]);- expect(mockBaseDelete).toHaveBeenCalledWith("contact_notes", {- id: 8,- 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.tsindex 169e6ffb..03977e72 100644--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts@@ -1,7 +1,6 @@import { supabaseDataProvider } from "ra-supabase-core";import {withLifecycleCallbacks,- type DataProvider,type GetListParams,type Identifier,type ResourceCallbacks,@@ -54,41 +53,6 @@ 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", {- resource,- noteId: params.id,- error,- });- throw new Error("Failed to delete note attachments");- }-- return params;-};-const dataProviderWithCustomMethods = {...baseDataProvider,async getList(resource: string, params: GetListParams) {@@ -299,8 +263,6 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [}return data;},- beforeDelete: async (params, dataProvider, resource) =>- deleteNoteAttachments(params, dataProvider, resource),},{resource: "deal_notes",@@ -312,8 +274,6 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [}return data;},- beforeDelete: async (params, dataProvider, resource) =>- deleteNoteAttachments(params, dataProvider, resource),},{resource: "sales",@@ -414,69 +374,6 @@ 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;- }-- // If we only have `src`, recover the file path after the attachments bucket segment.- const storagePath = extractPathFromStorageUrl(attachment.src);- if (storagePath) {- return storagePath;- }-- return null;-};--const extractPathFromStorageUrl = (src: string) => {- const pathname = getPathname(src);- if (!pathname) {- return null;- }-- const bucketSegment = `/${ATTACHMENTS_BUCKET}/`;- const bucketIndex = pathname.lastIndexOf(bucketSegment);- if (bucketIndex < 0) {- return null;- }-- // Convert `.../attachments/<file>` into `<file>`.- const path = pathname.slice(bucketIndex + bucketSegment.length);- return path.length > 0 ? safelyDecodePath(path) : null;-};--const getPathname = (value: string) => {- try {- return new URL(value, "http://localhost").pathname;- } catch {- return null;- }-};--const safelyDecodePath = (path: string) => {- try {- return decodeURIComponent(path);- } catch {- return path;- }-};-const uploadToBucket = async (fi: RAFile) => {if (!fi.src.startsWith("blob:") && !fi.src.startsWith("data:")) {// Sign URL check if path exists in the bucket