Skip to content

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

delete note attachments via db-triggered edge function

Anibal Svarcas24ee6802488c
diff --git a/supabase/config.toml b/supabase/config.toml
index 02fc4547..022e072a 100644
--- a/supabase/config.toml
+++ b/supabase/config.toml
@@ -157,6 +157,8 @@ s3_secret_key = "env(S3_SECRET_KEY)"
[functions.merge_contacts]
verify_jwt = false
+[functions.delete_note_attachments]
+verify_jwt = false
[functions.postmark]
verify_jwt = false
[functions.update_password]
diff --git a/supabase/functions/.env b/supabase/functions/.env
index c07bcf9c..29391ddf 100644
--- a/supabase/functions/.env
+++ b/supabase/functions/.env
@@ -9,3 +9,4 @@ POSTMARK_WEBHOOK_AUTHORIZED_IPS=3.134.147.250,50.31.156.6,50.31.156.77,18.217.20
SB_JWT_ISSUER=http://127.0.0.1:54321/auth/v1
SB_PUBLISHABLE_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH
SB_SECRET_KEY=sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz
+ATTACHMENTS_WEBHOOK_SECRET=atomic-crm-note-attachments-webhook-secret
diff --git a/supabase/functions/delete_note_attachments/index.ts b/supabase/functions/delete_note_attachments/index.ts
new file mode 100644
index 00000000..38629345
--- /dev/null
+++ b/supabase/functions/delete_note_attachments/index.ts
@@ -0,0 +1,156 @@
+import "jsr:@supabase/functions-js/edge-runtime.d.ts";
+import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";
+
+const ATTACHMENTS_BUCKET = "attachments";
+const WEBHOOK_SECRET_HEADER = "x-webhook-secret";
+const DEFAULT_WEBHOOK_SECRET = "atomic-crm-note-attachments-webhook-secret";
+
+type NoteAttachment = {
+ path?: string | null;
+ src?: string | null;
+};
+
+type NoteRecord = {
+ id?: number | string | null;
+ attachments?: NoteAttachment[] | null;
+};
+
+type WebhookPayload = {
+ type?: string | null;
+ table?: string | null;
+ schema?: string | null;
+ old_record?: NoteRecord | null;
+ record?: NoteRecord | null;
+};
+
+Deno.serve(async (req: Request) => {
+ if (req.method !== "POST") {
+ return jsonResponse({ error: "Method Not Allowed" }, 405);
+ }
+
+ const expectedSecret = Deno.env.get("ATTACHMENTS_WEBHOOK_SECRET");
+ const receivedSecret = req.headers.get(WEBHOOK_SECRET_HEADER);
+ const acceptedSecrets = [expectedSecret, DEFAULT_WEBHOOK_SECRET].filter(
+ (secret): secret is string => Boolean(secret),
+ );
+ if (!receivedSecret || !acceptedSecrets.includes(receivedSecret)) {
+ console.error("delete_note_attachments.unauthorized", {
+ hasExpectedSecret: Boolean(expectedSecret),
+ hasReceivedSecret: Boolean(receivedSecret),
+ });
+ return jsonResponse({ error: "Unauthorized" }, 401);
+ }
+
+ const payload = (await req.json()) as WebhookPayload;
+ const paths = getPathsToDelete(payload);
+ const noteId = payload.old_record?.id ?? payload.record?.id ?? null;
+
+ if (paths.length === 0) {
+ return jsonResponse({
+ status: "skipped",
+ reason: "no_paths_to_delete",
+ type: payload.type ?? null,
+ table: payload.table ?? null,
+ noteId,
+ });
+ }
+
+ const { error } = await supabaseAdmin.storage
+ .from(ATTACHMENTS_BUCKET)
+ .remove(paths);
+
+ if (error) {
+ console.error("delete_note_attachments.remove_error", {
+ type: payload.type ?? null,
+ table: payload.table ?? null,
+ noteId,
+ paths,
+ error,
+ });
+ return jsonResponse({ error: "Failed to delete note attachments" }, 500);
+ }
+
+ return jsonResponse({
+ status: "ok",
+ type: payload.type ?? null,
+ table: payload.table ?? null,
+ noteId,
+ deletedPathsCount: paths.length,
+ });
+});
+
+const getPathsToDelete = (payload: WebhookPayload): string[] => {
+ const oldPaths = extractAttachmentPaths(payload.old_record?.attachments);
+ const newPaths = extractAttachmentPaths(payload.record?.attachments);
+
+ if (payload.type === "UPDATE") {
+ const newPathsSet = new Set(newPaths);
+ return oldPaths.filter((path) => !newPathsSet.has(path));
+ }
+
+ if (payload.type === "DELETE") {
+ return oldPaths;
+ }
+
+ return [];
+};
+
+const extractAttachmentPaths = (
+ attachments?: NoteAttachment[] | 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?: NoteAttachment | null) => {
+ if (!attachment) {
+ return null;
+ }
+
+ if (attachment.path) {
+ return attachment.path;
+ }
+
+ if (!attachment.src) {
+ return null;
+ }
+
+ const pathname = getPathname(attachment.src);
+ if (!pathname) {
+ return null;
+ }
+
+ const bucketSegment = `/${ATTACHMENTS_BUCKET}/`;
+ const bucketIndex = pathname.lastIndexOf(bucketSegment);
+ if (bucketIndex < 0) {
+ return null;
+ }
+
+ 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 jsonResponse = (data: unknown, status = 200) =>
+ new Response(JSON.stringify(data), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
diff --git a/supabase/migrations/20260220154000_note_attachments_webhooks.sql b/supabase/migrations/20260220154000_note_attachments_webhooks.sql
new file mode 100644
index 00000000..6b55f01d
--- /dev/null
+++ b/supabase/migrations/20260220154000_note_attachments_webhooks.sql
@@ -0,0 +1,105 @@
+CREATE EXTENSION IF NOT EXISTS pg_net;
+
+DROP TRIGGER IF EXISTS on_contact_notes_deleted_delete_note_attachments
+ON public.contact_notes;
+
+DROP TRIGGER IF EXISTS on_deal_notes_deleted_delete_note_attachments
+ON public.deal_notes;
+
+DROP TRIGGER IF EXISTS on_contact_notes_changed_delete_note_attachments
+ON public.contact_notes;
+
+DROP TRIGGER IF EXISTS on_deal_notes_changed_delete_note_attachments
+ON public.deal_notes;
+
+CREATE OR REPLACE FUNCTION public.atomic_crm_note_attachments_webhook_url()
+RETURNS text
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ issuer text;
+ project_ref text;
+ function_url text;
+BEGIN
+ issuer := nullif(current_setting('request.jwt.claim.iss', true), '');
+
+ IF issuer IS NOT NULL THEN
+ issuer := regexp_replace(issuer, '/+$', '');
+ IF issuer LIKE '%/auth/v1' THEN
+ function_url := regexp_replace(
+ issuer,
+ '/auth/v1$',
+ '/functions/v1/delete_note_attachments'
+ );
+
+ IF function_url ~ '^http://(127\\.0\\.0\\.1|localhost):' THEN
+ RETURN regexp_replace(
+ function_url,
+ '^http://(127\\.0\\.0\\.1|localhost):',
+ 'http://host.docker.internal:'
+ );
+ END IF;
+
+ RETURN function_url;
+ END IF;
+ END IF;
+
+ project_ref := nullif(current_setting('app.settings.project_ref', true), '');
+ IF project_ref IS NOT NULL THEN
+ RETURN format(
+ 'https://%s.supabase.co/functions/v1/delete_note_attachments',
+ project_ref
+ );
+ END IF;
+
+ RETURN 'http://host.docker.internal:54321/functions/v1/delete_note_attachments';
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION public.atomic_crm_notify_note_attachment_cleanup()
+RETURNS trigger
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ payload jsonb;
+BEGIN
+ payload := jsonb_build_object(
+ 'old_record', OLD,
+ 'record', NEW,
+ 'type', TG_OP,
+ 'table', TG_TABLE_NAME,
+ 'schema', TG_TABLE_SCHEMA
+ );
+
+ PERFORM net.http_post(
+ url := public.atomic_crm_note_attachments_webhook_url(),
+ body := payload,
+ params := '{}'::jsonb,
+ headers := jsonb_build_object(
+ 'Content-Type',
+ 'application/json',
+ 'x-webhook-secret',
+ 'atomic-crm-note-attachments-webhook-secret'
+ ),
+ timeout_milliseconds := 1000
+ );
+
+ IF TG_OP = 'DELETE' THEN
+ RETURN OLD;
+ END IF;
+
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER on_contact_notes_changed_delete_note_attachments
+AFTER DELETE OR UPDATE ON public.contact_notes
+FOR EACH ROW
+EXECUTE FUNCTION public.atomic_crm_notify_note_attachment_cleanup();
+
+CREATE TRIGGER on_deal_notes_changed_delete_note_attachments
+AFTER DELETE OR UPDATE ON public.deal_notes
+FOR EACH ROW
+EXECUTE FUNCTION public.atomic_crm_notify_note_attachment_cleanup();