
drop view rhnWebContactEnabled;
drop view rhnUserReceiveNotifications;
drop view rhnWebContactDisabled;
drop view rhn_contact_monitoring;

alter table web_contact alter password type varchar(110);

create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;

create or replace view rhn_contact_monitoring as
select  u.id                    as recid,
        u.org_id                as customer_id,
        wupi.last_name          as contact_last_name,
        wupi.first_names        as contact_first_name,
        wupi.email          as email_address,
        u.login                 as username,
        u.password              as password,
        1                       as schedule_id,
        'GMT' || ''                     as preferred_time_zone
from
        web_user_personal_info wupi,
        web_contact u
where   u.id = wupi.web_user_id
        --  and some logic here to check org id for entitlements?
;
