Skip to content

Commit

Permalink
Archive document rpc
Browse files Browse the repository at this point in the history
  • Loading branch information
lwjameson committed Aug 22, 2024
1 parent b5a4db1 commit e85b574
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
32 changes: 32 additions & 0 deletions SQL Scripts/functions/archive_document_rpc.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
CREATE
OR REPLACE FUNCTION archive_document_rpc (
_document_id uuid
) RETURNS BOOLEAN AS $body$
DECLARE
_row public.documents % rowtype;
BEGIN
-- Check project policy that project documents can be updated by this user
IF NOT (check_action_policy_organization(auth.uid(), 'documents', 'UPDATE'))
THEN
RETURN FALSE;
END IF;

-- Get the document
SELECT * INTO _row FROM public.documents d WHERE d.id = _document_id;

-- If the user is the creator or an Org Admin, archive the document
IF _row.created_by = auth.uid() OR is_admin_organization(auth.uid())
THEN
IF NOT EXISTS(SELECT 1 FROM public.project_documents pd WHERE pd.id = _document_id AND pd.is_archived IS FALSE )
THEN
UPDATE public.documents d
SET is_archived = TRUE
WHERE d.id = _document_id;

RETURN TRUE;
END IF;
END IF;

RETURN FALSE;
END
$body$ LANGUAGE plpgsql SECURITY DEFINER;
38 changes: 38 additions & 0 deletions supabase/migrations/20240816204533_archive_document_rpc.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
set check_function_bodies = off;

CREATE OR REPLACE FUNCTION public.archive_document_rpc(_document_id uuid)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
AS $function$
DECLARE
_row public.documents % rowtype;
BEGIN
-- Check project policy that project documents can be updated by this user
IF NOT (check_action_policy_organization(auth.uid(), 'documents', 'UPDATE'))
THEN
RETURN FALSE;
END IF;

-- Get the document
SELECT * INTO _row FROM public.documents d WHERE d.id = _document_id;

-- If the user is the creator or an Org Admin, archive the document
IF _row.created_by = auth.uid() OR is_admin_organization(auth.uid())
THEN
IF NOT EXISTS(SELECT 1 FROM public.project_documents pd WHERE pd.id = _document_id AND pd.is_archived IS FALSE )
THEN
UPDATE public.documents d
SET is_archived = TRUE
WHERE d.id = _document_id;

RETURN TRUE;
END IF;
END IF;

RETURN FALSE;
END
$function$
;


0 comments on commit e85b574

Please sign in to comment.