---------------------------------------------------------------------------------
-- tblContCompWeb - Attach items to company as im_note
---------------------------------------------------------------------------------

create or replace function inline_0 ()
returns integer as '
DECLARE
        row			RECORD;
	v_person_id		integer;
	v_note_id		integer;
	v_note_type_id		integer;
	v_note_text		text;
BEGIN
    for row in
        select	*
	from	"tblContCompWeb" w,
		"tblContComp" cc,
		"tblContMaster" m
	where
		w."ContCompID" = cc."ContCompID"
		and cc."ContID" = m."ContID"
		and "CoordTypeID" != 0
		and lower(w."WebAdd") not in (
			select lower("WebAdd")
			from "tblContCompWeb" 
			where "CoordTypeID" = 31 
			group by lower("WebAdd")
			having count(*) > 1
		)
    loop
	select	person_id into v_person_id
	from	persons
	where	lxc_contact_id = row."ContID";

	select	category_id into v_note_type_id
	from	im_categories 
	where	aux_int1 = row."CoordTypeID"
		and category_type = ''Intranet Notes Type'';

	RAISE NOTICE ''ContCompWeb: Note: comp=%, pid=%, type=%, tid=%, web=%'', 
	row."CompID", v_person_id, row."CoordTypeID", v_note_type_id, row."WebAdd";

	v_note_text :=	replace(coalesce(row."WebAdd", ''''), '' '', ''_'') || '' '' || 
			coalesce(row."WebNotes", '''');

	IF v_person_id is not null THEN
		IF row."CoordTypeID" = 31 THEN
			update parties set email = row."WebAdd"
			where party_id = v_person_id;
			RAISE NOTICE ''Note: email updated: uid=%, email=%'', v_person_id, row."WebAdd";
		END IF;

		IF row."CoordTypeID" = 32 THEN
			update parties set url = row."WebAdd"
			where party_id = v_person_id;
			RAISE NOTICE ''Note: url updated: uid=%, url=%'', v_person_id, row."WebAdd";
		END IF;

		select	note_id into v_note_id
		from	im_notes
		where	object_id = v_person_id
			and note = v_note_text;
	
		IF v_note_id is NULL THEN
		    v_note_id := im_note__new(
			null, ''im_note'', now(),
			624, ''0.0.0.0'', null, 
			v_note_text,
			v_person_id,
			v_note_type_id, 11400
		    );
		END IF;
    ELSE
	RAISE NOTICE ''Note: Unknown user=%'', row."ContID";
    END IF;

    end loop;
    return 0;
END;' language 'plpgsql';
select inline_0 ();
drop function inline_0 ();

