/**
  @file
  @brief send alerts
  @details Send emails to users on review, approve, and/or reject

  @param alert_event= either SUBMITTED, APPROVED or REJECTED
  @param alert_lib= the library of the table being submitted
  @param alert_ds= the table submitted
  @param dsid= the staging reference for the submitted table

  <h4> SAS Macros </h4>
  @li mf_getattrn.sas
  @li mf_existds.sas
  @li mf_getuser.sas

  @version 9.4
  @author 4GL Apps Ltd
  @copyright 4GL Apps Ltd.  This code may only be used within Data Controller
    and may not be re-distributed or re-sold without the express permission of
    4GL Apps Ltd.

**/


%macro mpe_alerts(alert_event=
  , alert_lib=
  , alert_ds=
  , dsid=
);

/* exit if not configured */
%global DC_EMAIL_ALERTS;
%if &DC_EMAIL_ALERTS ne YES %then %do;
  %put DCNOTE: Email alerts are not configured;
  %put DCNOTE: (dc_email_alerts=&dc_email_alerts in &mpelib..mpe_config);
  %return;
%end;


%let alert_event=%upcase(&alert_event);
%let alert_lib=%upcase(&alert_lib);
%let alert_ds=%upcase(&alert_ds);
%let from_user=%mf_getuser();


/* get users TO which the email should be sent */

proc sql noprint;
create table work.users as select distinct a.alert_user,
        b.user_displayname,
        b.user_email
  from &mpelib..mpe_alerts
    (where=(&dc_dttmtfmt. lt tx_to)) a
  left join &mpelib..mpe_emails
    (where=(&dc_dttmtfmt. lt tx_to)) b
  on upcase(trim(a.alert_user))=upcase(trim(b.user_name))
  where a.alert_event in ("&alert_event","*ALL*")
    and a.alert_lib in ("&alert_lib","*ALL*")
    and a.alert_ds in ("&alert_ds","*ALL*");

/* ensure the submitter is included on the email */
%local isThere userdisp user_eml;
%let isThere=0;
select count(*) into: isThere from &syslast where alert_user="&from_user";
%if &isThere=0 %then %do;
  select user_displayname, user_email
    into: userdisp trimmed, :user_eml trimmed
    from &mpelib..mpe_emails
    where &dc_dttmtfmt. lt tx_to
      and user_name="&from_user";
  insert into work.users
    set alert_user="&from_user"
      ,user_displayname="&userdisp"
      ,user_email="&user_eml";
%end;


/* if no email / displayname is provided, then extract from metadata */
data work.emails;
  set work.users;
  length emailuri uri text $256; call missing(emailuri,uri); drop emailuri uri;

  /* get displayname */
  text=cats("omsobj:Person?@Name='",alert_user,"'");
  if metadata_getnobj(text,1,uri)<=0 then do;
    putlog "DCWARN: &from_user not found";
    return;
  end;
  else if user_displayname = '' then do;
    if metadata_getattr(uri,'DisplayName',user_displayname)<0 then do;
      putlog 'DCWARN: strange err, no displayname attribute of user URI';
    end;
  end;

  if index(user_email,'@') then return;
  /* get email from metadata if not in input table */
  if metadata_getnasn(uri,"EmailAddresses",1,emailuri)<=0 then do;
    putlog "DCWARN: " alert_user " has no emails in MPE_EMAILS or metadata!";
  end;
  else do;
    if metadata_getattr(emailuri,"Address",user_email)<0 then do;
      putlog 'DCWARN:  Unexpected error!  Valid emailURI but no email.  Weird.';
    end;
  end;
  /* only keep valid emails */
  if index(user_email,'@') ;
  /* dump contents for debugging */
  if _n_<21 then putlog (_all_)(=);
run;

%local emails;
proc sql noprint;
select quote(trim(user_email)) into: emails separated by ' ' from work.emails;

/* exit if nobody to email */
%if %mf_getattrn(emails,NLOBS)=0 %then %do;
  %put NOTE: No alerts configured (mpe_alerts.sas);
  %return;
%end;

/* display email options */
data _null_;
  set sashelp.voption(where=(group='EMAIL'));
  put optname '=' setting;
run;

filename __out email (&emails)
  subject="Table &alert_lib..&alert_ds has been &alert_event";

data work.alertmessage;
  set &mpelib..mpe_config;
  where &dc_dttmtfmt. lt tx_to;
  where also var_scope='DC_EMAIL' and var_name="&alert_event._TEMPLATE";
run;
%local SUBMITTED_TXT;
%if &alert_event=SUBMITTED %then %do;
  data _null_;
    set &mpelib..mpe_submit;
    where table_id="&dsid" and submit_status_cd='SUBMITTED';
    call symputx('SUBMITTED_TXT',submitted_reason_txt,'l');
  run;
  data _null_;
    File __out lrecl=32000;
    length txt $2048;
  %if %mf_getattrn(alertmessage,NLOBS)=0 %then %do;
    put 'Dear user,';
    put ' ';
    put "Please be advised that a change to table &alert_lib..&alert_ds has "
        "been proposed by &from_user on the &syshostname SAS server.";
    put " ";
    txt=symget('SUBMITTED_TXT');
    put "Reason provided: " txt;
    put " ";
    put "This is an automated email by Data Controller for SAS. For "
      "documentation, please visit https://docs.datacontroller.io";
  %end;
  %else %do;
    /* take template from config table */
    set work.alertmessage;
    cnt=countw(var_value,'0A'x);
    do i=1 to cnt;
      txt=resolve(scan(var_value,i,'0A'x));
      put txt /;
    end;
  %end;
  run;
%end;
%else %if &alert_event=APPROVED %then %do;
  /* there is no approval message */
  data _null_;
    File __out lrecl=32000;
    length txt $2048;
  %if %mf_getattrn(alertmessage,NLOBS)=0 %then %do;
    /* fallback message */
    put 'Dear user,';
    put ' ';
    put "Please be advised that a change to table &alert_lib..&alert_ds has "
        "been approved by &from_user on the &syshostname SAS server.";
    put " ";
    put "This is an automated email by Data Controller for SAS. For "
      "documentation, please visit https://docs.datacontroller.io";
  %end;
  %else %do;
    /* take template from config table */
    set work.alertmessage;
    cnt=countw(var_value,'0A'x);
    do i=1 to cnt;
      txt=resolve(scan(var_value,i,'0A'x));
      put txt /;
    end;
  %end;
  run;
%end;
%else %if &alert_event=REJECTED %then %do;
  data _null_;
    set &mpelib..mpe_review;
    where table_id="&dsid" and review_status_id='REJECTED';
    call symputx('REVIEW_REASON_TXT',REVIEW_REASON_TXT,'l');
  run;
  data _null_;
    File __out lrecl=32000;
    length txt $2048;
  %if %mf_getattrn(alertmessage,NLOBS)=0 %then %do;
    /* fallback message */
    put 'Dear user,';
    put ' ';
    put "Please be advised that a change to table &alert_lib..&alert_ds has "
        "been rejected by &from_user on the &syshostname SAS server.";
    put " ";
    txt=symget('REVIEW_REASON_TXT');
    put "Reason provided: " txt;
    put " ";
    put "This is an automated email by Data Controller for SAS. For "
      "documentation, please visit https://docs.datacontroller.io";
  %end;
  %else %do;
    /* take template from config table */
    set work.alertmessage;
    cnt=countw(var_value,'0A'x);
    do i=1 to cnt;
      txt=resolve(scan(var_value,i,'0A'x));
      put txt /;
    end;
  %end;
  run;
%end;

filename __out clear;

%mend mpe_alerts ;