104 lines
2.3 KiB
PL/PgSQL
104 lines
2.3 KiB
PL/PgSQL
CREATE OR REPLACE FUNCTION medreport.insert_company_params_on_new_company()
|
|
RETURNS trigger
|
|
LANGUAGE plpgsql
|
|
AS $function$
|
|
BEGIN
|
|
IF (TG_OP = 'INSERT' AND NEW.slug IS NOT NULL) THEN
|
|
INSERT INTO medreport.company_params (
|
|
account_id,
|
|
slug,
|
|
benefit_occurance,
|
|
benefit_amount
|
|
) VALUES (
|
|
NEW.id,
|
|
NEW.slug,
|
|
NULL,
|
|
NULL
|
|
);
|
|
END IF;
|
|
|
|
RETURN NEW;
|
|
END;
|
|
$function$
|
|
;
|
|
|
|
grant execute on function medreport.insert_company_params_on_new_company() to authenticated,
|
|
service_role;
|
|
|
|
create or replace function medreport.create_team_account (
|
|
account_name text,
|
|
new_personal_code text
|
|
) returns medreport.accounts
|
|
security definer
|
|
set search_path = ''
|
|
as $$
|
|
declare
|
|
existing_account medreport.accounts;
|
|
current_user uuid := (select auth.uid())::uuid;
|
|
new_account medreport.accounts;
|
|
begin
|
|
if not medreport.is_set('enable_team_accounts') then
|
|
raise exception 'Team accounts are not enabled';
|
|
end if;
|
|
|
|
-- Try to find existing account
|
|
select *
|
|
into existing_account
|
|
from medreport.accounts
|
|
where personal_code = new_personal_code
|
|
limit 1;
|
|
|
|
-- If not found, fail
|
|
if not found then
|
|
raise exception 'No account found with personal_code = %', new_personal_code;
|
|
end if;
|
|
|
|
insert into medreport.accounts(
|
|
name,
|
|
is_personal_account,
|
|
primary_owner_user_id)
|
|
values (
|
|
account_name,
|
|
false,
|
|
existing_account.id)
|
|
returning
|
|
* into new_account;
|
|
|
|
-- Insert membership
|
|
insert into medreport.accounts_memberships (
|
|
user_id,
|
|
account_id,
|
|
account_role,
|
|
created_by,
|
|
updated_by,
|
|
created_at,
|
|
updated_at,
|
|
has_seen_confirmation
|
|
)
|
|
values (
|
|
existing_account.id,
|
|
new_account.id,
|
|
'owner',
|
|
null,
|
|
null,
|
|
now(),
|
|
now(),
|
|
false
|
|
)
|
|
on conflict do nothing;
|
|
|
|
return new_account;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
grant execute on function medreport.create_team_account (text, text) to authenticated, service_role;
|
|
|
|
ALTER TABLE "medreport"."accounts"
|
|
DROP CONSTRAINT "accounts_primary_owner_user_id_fkey";
|
|
|
|
ALTER TABLE "medreport"."accounts"
|
|
ADD CONSTRAINT "accounts_primary_owner_user_id_fkey"
|
|
FOREIGN KEY (primary_owner_user_id)
|
|
REFERENCES auth.users(id)
|
|
ON DELETE CASCADE;
|