-- Deploy numerus:edit_contact to pg -- requires: schema_numerus -- requires: email -- requires: extension_uri -- requires: country_code -- requires: tag_name -- requires: contact -- requires: extension_vat -- requires: extension_pg_libphonenumber -- requires: tax_details begin; set search_path to numerus, public; create or replace function edit_contact(contact_slug uuid, name text, phone text, email email, web uri, tax_details tax_details, tags tag_name[]) returns uuid as $$ declare cid integer; company integer; begin update contact set name = edit_contact.name , tags = edit_contact.tags where slug = contact_slug returning contact_id, company_id into cid, company ; if cid is null then return null; end if; if tax_details is null then delete from contact_tax_details where contact_id = cid ; else insert into contact_tax_details (contact_id, business_name, vatin, address, city, province, postal_code, country_code) values (cid, tax_details.business_name, (tax_details.country_code || tax_details.vatin)::vatin, tax_details.address, tax_details.city, tax_details.province, tax_details.postal_code, tax_details.country_code) on conflict (contact_id) do update set business_name = excluded.business_name , vatin = excluded.vatin , address = excluded.address , city = excluded.city , province = excluded.province , postal_code = excluded.postal_code , country_code = excluded.country_code ; end if; if phone is null or trim(phone) = '' then delete from contact_phone where contact_id = cid ; else insert into contact_phone (contact_id, phone) values (cid, parse_packed_phone_number(edit_contact.phone, coalesce(tax_details.country_code, 'ES'))) on conflict (contact_id) do update set phone = excluded.phone ; end if; if email is null or trim(email) = '' then delete from contact_email where contact_id = cid ; else insert into contact_email (contact_id, email) values (cid, edit_contact.email) on conflict (contact_id) do update set email = excluded.email ; end if; if web is null or web = '' then delete from contact_web where contact_id = cid ; else insert into contact_web (contact_id, uri) values (cid, edit_contact.web) on conflict (contact_id) do update set uri = excluded.uri ; end if; return contact_slug; end $$ language plpgsql ; revoke execute on function edit_contact(uuid, text, text, email, uri, tax_details, tag_name[]) from public; grant execute on function edit_contact(uuid, text, text, email, uri, tax_details, tag_name[]) to invoicer; grant execute on function edit_contact(uuid, text, text, email, uri, tax_details, tag_name[]) to admin; drop function if exists edit_contact(uuid, text, text, text, text, email, uri, text, text, text, text, country_code, tag_name[]); commit;