Loading...
Searching...
No Matches
mpe_loader.sas
Go to the documentation of this file.
1/**
2 @file
3 @brief Loads CSV and sends to the staging area for approval
4 @details this macro used to capture multiple CSVs (eg from one excel file) in
5 a staging area and send them all to a landing area. For simplicity this
6 functionality is now deprecated, and each load should be made as a seperate
7 request. If there is a use case to load multiple tables at once, the client
8 should manage this and load them seperately.
9
10 @param url= used for debugging (provided by stagedata stp)
11 @param dlm= use to provide alternative delimeters for CSVs (not just comma)
12 @param [in] termstr= (crlf) Always crlf from adapter, whereas loadfile service
13 figures it out
14
15 <h4> SAS Macros </h4>
16 @li dc_assignlib.sas
17 @li mf_getattrn.sas
18 @li mf_getuser.sas
19 @li mf_verifymacvars.sas
20 @li mp_abort.sas
21 @li mp_cntlout.sas
22 @li mp_dirlist.sas
23 @li mp_lockanytable.sas
24 @li mpe_accesscheck.sas
25 @li mpe_alerts.sas
26 @li mpe_xlmapvalidate.sas
27 @li mpe_loadfail.sas
28 @li mpe_runhook.sas
29
30 @version 9.2
31 @author 4GL Apps Ltd
32 @copyright 4GL Apps Ltd. This code may only be used within Data Controller
33 and may not be re-distributed or re-sold without the express permission of
34 4GL Apps Ltd.
35
36 @sasjslint {"maxLineLength": 82}
37
38**/
39
40%macro mpe_loader(
41 mperef= /* name of subfolder containing the staged data */
42 ,mDebug=0 /* set to 1 for development or debugging */
43 ,submitted_reason_txt= /* populates column of same name in sumo_approvals*/
44 ,approver= /* allows a userid to be provided for direct approval email */
45 ,url= /* optional - url for debugging */
46 ,dlm=%str(,)
47 ,termstr=crlf
48 ,dc_dttmtfmt=E8601DT26.6
49 );
50%put entered mpe_loader from &=_program;
51%put &=url;
52%put &=termstr;
53%put &=dlm;
54 /* determine full path to CSV directory */
55%local now;
56%let now=&dc_dttmtfmt;
57%put &=now;
58
59/**
60 * get full path to package (only subdirectory passed through)
61 */
62%mp_abort(
63 iftrue=(%mf_verifymacvars(mperef mpelocapprovals)=0)
64 ,mac=bitemporal_dataloader
65 ,msg=%str(Missing: mperef mpelocapprovals)
66)
67
68%let csv_dir=%trim(&mpelocapprovals/&mperef);
69
70/* exit if package has already been uploaded */
71%local check;
72proc sql noprint;
73select count(*) into: check
74 from &mpelib..mpe_loads
75 where csv_dir="&mperef";
76%if &check %then %do;
77 %mp_abort(msg=Folder &mperef already has an entry in &mpelib..mpe_loads
78 ,mac=mpe_loader.sas);
79 %return;
80%end;
81
82/* get CSV directory contents */
83%mp_dirlist(path=&csv_dir,outds=WORK.getfiles)
84data WORK.csvs;
85 set WORK.getfiles;
86 if upcase(scan(filename,3,'.'))='CSV' then do;
87 lib=upcase(scan(filename,1,'.'));
88 ds=upcase(scan(filename,2,'.'));
89 output;
90 end;
91run;
92
93/* get table attributes */
94proc sql noprint;
95create table WORK.sumo_tables as
96 select a.filename, b.*
97 from WORK.csvs a
98 left join &mpelib..mpe_tables b
99 on a.lib=b.libref
100 and a.ds=b.dsn
101 where b.tx_from le &now
102 and &now lt b.tx_to;
103
104/* define user as meta user if available */
105%local user;
106%let user=%mf_getuser();
107
108/* check if there is actually a table to load */
109%if %mf_getattrn(WORK.sumo_tables,NLOBS)=0 %then %do;
110 %let msg=Table not registered in &mpelib..mpe_tables;
111 %mpe_loadfail(
112 status=&msg
113 ,now=&now
114 ,mperef=&mperef
115 ,dc_dttmtfmt=&dc_dttmtfmt.
116 )
117 %mp_abort(msg=&msg,mac=mpe_loader.sas);
118 %return;
119%end;
120
121proc sql;
122insert into &mpelib..mpe_loads
123 set USER_NM="&user"
124 ,STATUS='IN PROGRESS'
125 ,CSV_dir="&mperef"
126 ,PROCESSED_DTTM=&now
127 ,reason_txt = symget('submitted_reason_txt');
128
129
130/* import CSV */
131
132%let droplist=;
133%let attrib=;
134%let droplist=;
135%let libref=;
136%let DS=;
137
138/* get table info */
139data _null_;
140 set sumo_tables;
141 libds=upcase(cats(libref,'.',dsn));
142 call symputx('orig_libds',libds);
143 is_fmt=0;
144 if substr(cats(reverse(dsn)),1,3)=:'CF-' then do;
145 libds=scan(libds,1,'-');
146 putlog "Format Catalog Captured";
147 libds='work.fmtextract';
148 is_fmt=1;
149 end;
150 call symputx('is_fmt',is_fmt);
151 call symputx('libds',libds);
152 call symputx('FNAME',filename);
153 call symputx('LIBREF',libref);
154 call symputx('DS',dsn);
155 call symputx('LOADTYPE',loadtype);
156 call symputx('BUSKEY',buskey);
157 call symputx('VAR_TXFROM',var_txfrom);
158 call symputx('VAR_TXTO',var_txto);
159 call symputx('VAR_BUSFROM',var_busfrom);
160 call symputx('VAR_BUSTO',var_busto);
161 call symputx('VAR_PROCESSED',var_processed);
162 call symputx('RK_UNDERLYING',RK_UNDERLYING);
163 call symputx('POST_EDIT_HOOK',POST_EDIT_HOOK);
164 call symputx('NOTES',NOTES);
165 call symputx('PK',coalescec(RK_UNDERLYING,buskey));
166 call symputx('NUM_OF_APPROVALS_REQUIRED',NUM_OF_APPROVALS_REQUIRED,'l');
167 put (_all_)(=);
168 stop;
169run;
170
171%if %length(&ds)=0 %then %do;
172 %let msg=%str(ERR)OR: Unable to extract record from &mpelib..mpe_tables;
173 %mpe_loadfail(
174 status=FAILED
175 ,now=&now
176 ,mperef=&mperef
177 ,reason_txt=%quote(&msg)
178 ,dc_dttmtfmt=&dc_dttmtfmt.
179 )
180 %mp_abort(msg=&msg,mac=mpe_loader.sas);
181 %return;
182%end;
183
184/* export format catalog */
185%mp_cntlout(
186 iftrue=(&is_fmt=1)
187 ,libcat=&orig_libds
188 ,fmtlist=0
189 ,cntlout=work.fmtextract
190)
191
192/* user must have EDIT access to load a table */
193%mpe_accesscheck(&orig_libds
194 ,outds=work.sumo_access
195 ,user=&user
196 ,access_level=EDIT )
197%put exiting accesscheck;
198
199%if %mf_getattrn(work.sumo_access,NLOBS)=0 %then %do;
200 %let msg=%str(ERR)OR: User is not authorised to edit &orig_libds!;
201 %mpe_loadfail(
202 status=UNAUTHORISED
203 ,now=&now
204 ,mperef=&mperef
205 ,reason_txt=%quote(&msg)
206 ,dc_dttmtfmt=&dc_dttmtfmt.
207 )
208 %mp_abort(msg=&msg,mac=mpe_loader.sas);
209 %return;
210%end;
211
212%put now importing: "&csv_dir/&fname" termstr=&termstr;
213/* get the variables from the CSV */
214data vars_csv1(index=(idxname=(varnum name)) drop=infile);
215 infile "&csv_dir/&fname" lrecl=32767 dsd termstr=&termstr encoding='utf-8';
216 input;
217 length infile $32767;
218 infile=compress(_infile_,'"',);
219 infile=compress(infile,"'",);
220 format name $32.;
221 putlog 'received vars: ' infile;
222 call symputx('received_vars',infile,'l');
223 do varnum=1 to countw(infile,"&dlm");
224 /* keep writeable chars */
225 name=compress(upcase(scan(infile,varnum)),,'kw');
226 if name ne "_____DELETE__THIS__RECORD_____" then output;
227 end;
228 stop;
229run;
230%put received_vars = &received_vars;
231
232%dc_assignlib(WRITE,&libref)
233
234/* get list of variables and their formats */
235proc contents noprint data=&libds
236 out=vars(keep=name type length varnum format:);
237run;
238data vars(keep=name type length varnum format);
239 set vars(rename=(format=format2 type=type2));
240 name=upcase(name);
241 format2=upcase(format2);
242 /* not interested in transaction or processing dates
243 (append table must be supplied without them) */
244 if name not in ("&VAR_TXFROM","&VAR_TXTO","&VAR_PROCESSED"
245 ,"_____DELETE__THIS__RECORD_____");
246 if type2 in (2,6) then do;
247 length format $49.;
248 if format2='' then format=cats('$',length,'.');
249 else format=cats(format2,max(formatl,length),'.');
250 type='char';
251 end;
252 else do;
253 if format2='' then format=cats(length,'.');
254 else if format2=:'DATETIME' or format2=:'E8601DT' or format2=:'NLDATM'
255 then do;
256 format='DATETIME19.';
257 end;
258 else if format2=:'DATE' or format2=:'DDMMYY'
259 or format2=:'MMDDYY' or format2=:'YYMMDD'
260 or format2=:'E8601DA' or format2=:'B8601DA'
261 or format2=:'NLDATE'
262 then do;
263 format='DATE9.';
264 end;
265 else if format2='BEST' & formatl=0 then format=cats('BEST',length,'.');
266 else do;
267 if formatl=0 then formatl=length;
268 format=cats(format2,formatl,'.',formatd);
269 end;
270 type='num';
271 end;
272 put (_all_)(=);
273run;
274
275/* build attrib statement */
276data vars_attrib;
277 length attrib_statement $32767 type2 $20;
278 set vars end=lastobs;
279 retain attrib_statement;
280
281 if type='char' then type2='$';
282 str1=catx(' ',name,'length=',cats(type2,length));
283 attrib_statement=trim(attrib_statement)!!' '!!trim(str1);
284
285 if lastobs then call symputx('ATTRIB',attrib_statement,'L');
286run;
287
288/* build input statement - first get vars in right order
289 and join with target formats*/
290proc sql noprint;
291create table vars_csv2 as
292 select b.*
293 from vars_csv1 a
294 left join vars_attrib b
295 on a.name=b.name
296 order by a.varnum;
297
298
299/* now build input statement */
300data final_check;
301 set vars_csv2 end=lastobs;
302 length input_statement $32767 type2 $20 droplist $32767;
303 retain input_statement droplist;
304
305 /* Build input statement - CATCH EXCEPTIONS HERE!*/
306 if name in ('QUOTE_DTTM') then do;
307 name=cats(name,'2');
308 droplist=catx(' ',trim(droplist),name);
309 type2='$20.';/* converted below */
310 end;
311 else if type='char' then type2=cats('$CHAR', length,'.');
312 else if format='DATE9.' then type2='ANYDTDTE.';
313 else if format='DATETIME19.' then type2='ANYDTDTM.';
314 else if format=:'TIME' then type2='ANYDTTME.';
315 else if name='' then do;/* additional vars in input data */
316 name='_____DELETE__THIS__VARIABLE_____';
317 droplist=catx(' ',trim(droplist),'_____DELETE__THIS__VARIABLE_____');
318 type2='$1.';
319 end;
320 else type2='best32.';
321 /* else type2=cats(length,'.'); */
322
323 input_statement=catx(' ',input_statement,name,':',type2);
324
325 if lastobs then do;
326 call symputx('INPUT', input_statement,'L');
327 if trim(droplist) ne '' then
328 call symputx('droplist',"drop "!!droplist!!';','l');
329 end;
330run;
331
332%let mpeloadstop=0;
333
334data work.STAGING_DS;
335 &droplist;
336 infile "&csv_dir/&fname" dsd dlm="&dlm" lrecl=32767
337 firstobs=2 missover termstr=&termstr encoding='utf-8';
338 attrib _____DELETE__THIS__RECORD_____ length=$3 &attrib ;
339 if _n_=1 then call missing (of _all_);
340 missing a b c d e f g h i j k l m n o p q r s t u v w x y z _;
341 input
342 %if %scan(%quote(&received_vars),1)=_____DELETE__THIS__RECORD_____ %then %do;
343 _____DELETE__THIS__RECORD_____: $3.
344 %end;
345 &input;
346
347 %if %index(%quote(&attrib.),UNLIKELY_VAR ) %then %do;
348 /*UNLIKELY_VAR=input(UNLIKELY_VAR2,ANYDTDTM21.);*/
349 /* SPECIAL LOGIC FOR SPECIAL VARS */
350 %end;
351
352 if _error_ ne 0 then do;
353 putlog _infile_;
354 call symputx('mpeloadstop',_n_);
355 stop;
356 end;
357 /* remove all blank rows */
358 if compress(cats(of _all_),'.')=' ' then delete;
359run;
360
361%if &mpeloadstop>0 %then %do;
362 %if %symexist(SYSPRINTTOLOG) %then %let logloc=&SYSPRINTTOLOG;
363 %else %let logloc=%qsysfunc(getoption(LOG));
364 %put redirecting log output to capture return message;
365 %put currentloc=&logloc;
366 filename tmp temp;
367 proc printto log=tmp;run;
368 data _null_;
369 &droplist;
370 infile "&csv_dir/&fname" dsd dlm="&dlm" lrecl=32767 firstobs=2
371 missover termstr=&termstr;
372 attrib &attrib ;
373 input
374 %if %scan(%quote(&received_vars),1)=_____DELETE__THIS__RECORD_____
375 %then %do;
376 _____DELETE__THIS__RECORD_____: $3.
377 %end;
378 &input;
379 if _error_ then stop;
380 run;
381 /* get log back */
382 proc printto log=&logloc;run;
383 data _null_; infile tmp; input; putlog _infile_;run;
384 /* scan log for invalid data warnings */
385 data _null_;
386 infile tmp;
387 input;
388 length msg1 msg2 msg3 msg4 msg5 msg url $32767;
389 if index(_infile_,'NOTE: Invalid data for') then do;
390 msg1=_infile_;
391 input;
392 msg2=_infile_;
393 input;
394 msg3=_infile_;
395 input;
396 msg4=_infile_;
397 input;
398 msg5=_infile_;
399 url=symget('url');
400 msg=catx('\n',msg1,msg2,msg3,msg4,msg5,'\n',url);
401 call symputx('msg',msg);
402 stop;
403 end;
404 run;
405
406 %mpe_loadfail(
407 status=FAILED
408 ,now=&now
409 ,mperef=&mperef
410 ,reason_txt=%superq(msg)
411 ,dc_dttmtfmt=&dc_dttmtfmt.
412 )
413 %return;
414%end;
415
416/* check that the table is unique on PK */
417proc sort data=work.STAGING_DS dupout=work.MPE_DUPS (keep=&pk) nodupkey;
418 by &pk;
419run;
420%if %mf_getattrn(work.MPE_DUPS,NLOBS)>0 %then %do;
421 %local duplist;
422 data _null_;
423 set work.mpe_dups;
424 %do i=1 %to %sysfunc(countw(&pk));
425 %let iWord=%scan(&pk,&i);
426 call symputx('duplist',symget('duplist')!!
427 " &iWord="!!cats(&iWord));
428 %end;
429 run;
430 %let msg=This upload contains duplicates on the Primary Key columns %trim(
431 )(&pk) \n Please remove the duplicates and try again. %trim(
432 )\n &duplist \n ;
433 %mp_abort(msg=%superq(msg),mac=mpe_loader.sas);
434 %return;
435%end;
436
437%if &syscc gt 4 %then %do;
438 %let msg=SYSCC=&syscc prior to post edit hook (%superq(syserrortext));
439 %mpe_loadfail(
440 status=FAILED - &syscc
441 ,now=&now
442 ,mperef=&mperef
443 ,reason_txt=%superq(msg)
444 ,dc_dttmtfmt=&dc_dttmtfmt.
445 )
446 %return;
447%end;
448
449/* If a Complex Excel Upload, needs to have the load ref added to the table */
450%mpe_xlmapvalidate(&mperef,work.staging_ds,&mpelib,&orig_libds)
451
452/* Run the Post Edit Hook prior to creation of staging folder */
453%mpe_runhook(POST_EDIT_HOOK)
454
455/* stop if err */
456%if &syscc gt 4 %then %do;
457 %let msg=ERR in post edit hook (&post_edit_hook);
458 %mpe_loadfail(
459 status=FAILED - &syscc
460 ,now=&now
461 ,mperef=&mperef
462 ,reason_txt=%quote(&msg)
463 ,dc_dttmtfmt=&dc_dttmtfmt.
464 )
465 %return;
466%end;
467
468/* The post edit hook may have re-pointed the changeset at a different table -
469 * that is what lets an empty mirror stand in for a real one. The target must
470 * itself be registered in MPE_TABLES: the approval screen resolves the table's
471 * audit settings from that row, and a changeset whose base table has no row
472 * cannot be reviewed. Fail here, while the submitter is still watching. */
473%local target_chk;
474proc sql noprint;
475select count(*) into: target_chk
476 from &mpelib..mpe_tables
477 where tx_from le &now and &now lt tx_to
478 and upcase(libref)="%upcase(&libref)"
479 and upcase(dsn)="%upcase(&ds)";
480%if &target_chk=0 %then %do;
481 %let msg=%str(ERR)OR: target table &libref..&ds is not registered in%trim(
482 ) &mpelib..mpe_tables - a post edit hook may only route a changeset to a%trim(
483 ) registered table;
484 %mpe_loadfail(
485 status=FAILED - TARGET NOT REGISTERED
486 ,now=&now
487 ,mperef=&mperef
488 ,reason_txt=%quote(&msg)
489 ,dc_dttmtfmt=&dc_dttmtfmt.
490 )
491 %return;
492%end;
493
494
495/**
496 * send to approve process
497 */
498
499/* create a dataset key (datetime plus 3 digit random number plus PID) */
500
501/* send dataset to approvals subfolder with same name as subfolder */
502libname approval "&mpelocapprovals/&mperef";
503data approval.&mperef;
504 set work.staging_ds;
505run;
506proc export data=approval.&mperef
507 outfile="&mpelocapprovals/&mperef/&mperef..csv"
508 dbms=csv
509 replace;
510run;
511
512/* update the control dataset with relevant info */
513data append_app;
514 if 0 then set &mpelib..mpe_submit;/* get formats */
515 call missing (of _all_);
516 TABLE_ID="&mperef";
517 submit_status_cd='SUBMITTED';
518 submitted_by_nm="%mf_getuser()";
519 base_lib="&libref";
520 base_ds="&ds";
521 submitted_on_dttm=&now;
522 submitted_reason_txt=symget('submitted_reason_txt');
523 input_vars=%mf_getattrn(approval.&mperef,NVARS);
524 input_obs=%mf_getattrn(approval.&mperef,NLOBS);
525 num_of_approvals_required=&NUM_OF_APPROVALS_REQUIRED;
526 num_of_approvals_remaining=&NUM_OF_APPROVALS_REQUIRED;
527 reviewed_by_nm='';
528 reviewed_on_dttm=.;
529run;
530
531%mp_lockanytable(LOCK,lib=&mpelib,ds=mpe_submit,
532 ref=%str(&mperef update in &_program),
533 ctl_ds=&mpelib..mpe_lockanytable
534)
535proc append base= &mpelib..mpe_submit data=append_app;
536run;
537%mp_lockanytable(UNLOCK,
538 lib=&mpelib,ds=mpe_submit,
539 ctl_ds=&mpelib..mpe_lockanytable
540)
541
542/* send email to REVIEW members */
543%put sending mpe_alerts;
544%mpe_alerts(alert_event=SUBMITTED
545 , alert_lib=&libref
546 , alert_ds=&ds
547 , dsid=&mperef
548)
549/* DISABLE EMAIL FOR NOW
550 %let b2=REASON: %quote(&submitted_reason_txt);
551
552 %local URLNOTES;
553 %if %length(&notes)>0 %then %let URLNOTES=%quote(%sysfunc(urlencode(&notes)));
554
555 %let b3=%str(Click to review / approve: )%trim(
556 )%str(http://&_srvname:&_srvport&_url?_PROGRAM=/Web/approvals&)%trim(
557 )TABLEID=&dsid%str(&)BASETABLE=&libref..&ds%str(&)NOTES=&URLNOTES;
558
559 %let b4=%str(Reference ID: &mperef);
560*/
561
562%put mpe_loader finishing up with syscc=&syscc;
563%if &syscc le 4 %then %do;
564 %local dur;
565 data _null_;
566 now=symget('now');
567 dur=%sysfunc(datetime())-&now;
568 call symputx('dur',dur,'l');
569 putlog 'Updating mpe_loads with the following query:';
570 putlog "update &mpelib..mpe_loads set STATUS='SUCCESS'";
571 putlog " , duration=" dur;
572 putlog " , processed_dttm=" now;
573 putlog " , approvals = '&libref..&ds'";
574 putlog " where CSV_DIR='&mperef';";
575 run;
576 proc sql;
577 update &mpelib..mpe_loads set STATUS='SUCCESS'
578 , duration=&dur
579 , processed_dttm=&now
580 , approvals = "&libref..&ds"
581 where CSV_DIR="&mperef";
582%end;
583%else %do;
584 %mpe_loadfail(
585 status="FAILED - &syscc"
586 ,now=&now
587 ,approvals=&libref..&ds
588 ,mperef=&mperef
589 ,dc_dttmtfmt=&dc_dttmtfmt.
590 )
591 %return;
592%end;
593
594%mend mpe_loader;