changed due date format to fit older format - enabled emails by default
[Evergreen.git] / Evergreen / src / support-scripts / eg_gen_overdue.pl
1 #!/usr/bin/perl
2 # ---------------------------------------------------------------
3 # Generates the overdue notices XML file
4 # ./eg_gen_overdue.pl <bootstap> 0
5 #               generates today's notices
6 # ./eg_gen_overdue.pl <bootstap> 1 0
7 #               generates notices for today - 1 and today
8 # ./eg_gen_overdue.pl <bootstap> 2 1 0  
9 # ./eg_gen_overdue.pl <bootstap> 3 2 1 0  etc...
10 # ---------------------------------------------------------------
11
12
13
14 use strict; use warnings;
15 require '../../../Open-ILS/src/support-scripts/oils_header.pl';
16 use vars qw/$logger $apputils/;
17 use Data::Dumper;
18 use OpenILS::Const qw/:const/;
19 use DateTime;
20 use Email::Send;
21 use DateTime::Format::ISO8601;
22 use OpenSRF::Utils qw/:datetime/;
23 use Unicode::Normalize;
24 use OpenILS::Const qw/:const/;
25
26 my $SEND_EMAILS = 1;
27
28
29 my $bsconfig = shift || die "usage: $0 <bootstrap_config>\n";
30 my @goback = @ARGV;
31 @goback = (0) unless @goback;
32 osrf_connect($bsconfig);
33 my $e = OpenILS::Utils::CStoreEditor->new;
34
35 my $smtp = $ENV{EG_OVERDUE_SMTP_HOST};
36 my $mail_sender = $ENV{EG_OVERDUE_EMAIL_SENDER};
37
38 # ---------------------------------------------------------------
39 # Set up the email template
40 my $etmpl = $ENV{EG_OVERDUE_EMAIL_TEMPLATE};
41 my $email_template;
42 if( open(F,"$etmpl") ) {
43         my @etmpl = <F>;
44         $email_template = join('',@etmpl);
45         close(F);
46 }
47 # ---------------------------------------------------------------
48
49
50
51 my @date = CORE::localtime;
52 my $sec  = $date[0];
53 my $min  = $date[1];
54 my $hour = $date[2];
55 my $day  = $date[3];
56 my $mon  = $date[4] + 1;
57 my $year = $date[5] + 1900;
58
59 my %USER_CACHE;
60 my %ORG_CACHE;
61
62
63 print <<XML;
64 <?xml version='1.0' encoding='UTF-8'?>
65 <file type="notice" date="$mon/$day/$year" time="$hour:$min:$sec">
66         <agency name="PINES">
67 XML
68
69 print_notices($_) for @goback;
70
71 print <<XML;
72         </agency>
73 </file>
74 XML
75
76
77 # -----------------------------------------------------------------------
78 # -----------------------------------------------------------------------
79
80
81 sub print_notices {
82         my $goback = shift || 0;
83
84         for my $day ( qw/ 7 14 30 / ) {
85                 my ($start, $end) = make_date_range($day + $goback);
86
87                 $logger->info("OD_notice: process date range $start -> $end");
88
89                 my $query = [
90                         {
91                                 checkin_time => undef,
92                                 due_date => { between => [ $start, $end ] },
93                         #       stop_fines => { 'not in' => [ OILS_STOP_FINES_LOST, OILS_STOP_FINES_CLAIMSRETURNED ] }
94                         },
95                         { order_by => { circ => 'usr, circ_lib' } }
96                 ];
97                 my $circs = $e->search_action_circulation($query, {idlist=>1});
98
99                 process_circs( $circs, "${day}day" );
100         }
101 }
102
103
104 sub process_circs {
105         my $circs = shift;
106         my $range = shift;
107
108         return unless @$circs;
109
110         $logger->info("OD_notice: processing range $range and ".scalar(@$circs)." potential circs");
111
112         my $org; 
113         my $patron;
114         my @current;
115
116         my $x = 0;
117         for my $circ (@$circs) {
118                 $circ = $e->retrieve_action_circulation($circ);
119
120                 if( !defined $org or 
121                                 $circ->circ_lib != $org  or $circ->usr ne $patron ) {
122                         $org = $circ->circ_lib;
123                         $patron = $circ->usr;
124                         print_notice( $range, \@current ) if @current;
125                         @current = ();
126                 }
127
128                 push( @current, $circ );
129                 $x++;
130         }
131
132         $logger->info("OD_notice: processed $x circs");
133         print_notice( $range, \@current );
134 }
135
136 sub make_date_range {
137         my $daysback = shift;
138
139         my $epoch = CORE::time - ($daysback * 24 * 60 * 60);
140         my $date = DateTime->from_epoch( epoch => $epoch, time_zone => 'local');
141
142         $date->set_hour(0);
143         $date->set_minute(0);
144         $date->set_second(0);
145         my $start = "$date";
146         
147         $date->set_hour(23);
148         $date->set_minute(59);
149         $date->set_second(59);
150
151         return ($start, "$date");
152 }
153
154
155 sub print_notice {
156         my( $range, $circs ) = @_;
157         return unless @$circs;
158
159         my $s1 = scalar(@$circs);
160         
161         # we don't charge for lost or claimsreturned
162         $circs = [ grep {
163                 $_ ne OILS_STOP_FINES_LOST and
164                 $_ ne OILS_STOP_FINES_CLAIMSRETURNED } @$circs ];
165
166         return unless @$circs;
167
168         my $s2 = $s1 - scalar(@$circs);
169         $logger->info("OD_notice: dropped $s2 lost/CR from processing...") if $s2;
170
171         my $org = $circs->[0]->circ_lib;
172         my $usr = $circs->[0]->usr;
173         $logger->debug("OD_notice: printing $range user:$usr org:$org");
174
175         my @patron_data = fetch_patron_data($usr);
176         my @org_data = fetch_org_data($org);
177
178         my $email;
179
180         if( $email = $patron_data[0]->email 
181                 and $email =~ /.+\@.+/ 
182                 and ($range eq '7day' or $range eq '14day') ) {
183
184                         send_email($range, \@patron_data, \@org_data, $circs);
185
186         } else {
187
188                 print "\t\t<notice type='overdue' count='$range'>\n";
189                 print_patron_xml_chunk(@patron_data);
190                 print_org_xml_chunk(@org_data);
191                 print_circ_chunk($_) for @$circs;
192                 print "\t\t</notice>\n";
193         }
194 }
195
196
197 sub fetch_patron_data {
198         my $user_id = shift;
199
200         my $patron = $USER_CACHE{$user_id};
201
202         if( ! $patron ) {
203                 $logger->debug("OD_notice:   fetching patron $user_id");
204
205                 $patron = $e->retrieve_actor_user(
206                         [
207                                 $user_id,
208                                 {
209                                         flesh => 1,
210                                         flesh_fields => { 
211                                                 'au' => [qw/ card billing_address mailing_address /] 
212                                         }
213                                 }
214                         ]
215                 ) or return handle_event($e->event);
216
217                 $USER_CACHE{$user_id} = $patron;
218         }
219
220         my $bc = $patron->card->barcode;
221         my $fn = $patron->first_given_name;
222         my $mn = $patron->second_given_name;
223         my $ln = $patron->family_name;
224
225         my ( $s1, $s2, $city, $state, $zip );
226         my $baddr = $patron->mailing_address || $patron->billing_address;
227         if( $baddr ) {
228                 $s1             = $baddr->street1;
229                 $s2             = $baddr->street2;
230                 $city           = $baddr->city;
231                 $state  = $baddr->state;
232                 $zip            = $baddr->post_code;
233         }
234
235         $bc = entityize($bc);
236         $fn = entityize($fn);
237         $mn = entityize($mn);
238         $ln = entityize($ln);
239         $s1 = entityize($s1);
240         $s2 = entityize($s2);
241         $city  = entityize($city);
242         $state = entityize($state);
243         $zip     = entityize($zip);
244
245         return ( $patron, $bc, $fn, $mn, $ln, $s1, $s2, $city, $state, $zip );
246 }
247
248         
249 sub print_patron_xml_chunk {
250         my( $patron, $bc, $fn, $mn, $ln, $s1, $s2, $city, $state, $zip ) = @_;
251         my $pid = $patron->id;
252         print <<"       XML";
253                         <patron>
254                                 <id type="barcode">$bc</id>
255                                 <fullname>$fn $mn $ln</fullname>
256                                 <street1>$s1 $s2</street1>
257                                 <city_state_zip>$city, $state $zip</city_state_zip>
258                                 <sys_id>$pid</sys_id>
259                         </patron>
260         XML
261 }
262
263
264 sub fetch_org_data {
265         my $org_id = shift;
266
267         my $org = $ORG_CACHE{$org_id};
268
269         if( ! $org ) {
270                 $logger->debug("OD_notice:   fetching org $org_id");
271
272                 $org = $e->retrieve_actor_org_unit(
273                         [
274                                 $org_id,
275                                 {
276                                         flesh => 1, 
277                                         flesh_fields => 
278                                                 { aou => [ qw/billing_address mailing_address/ ] }
279                                 }
280                         ]
281                 ) or return handle_event($e->event);
282
283                 $ORG_CACHE{$org_id} = $org;
284         }
285
286         my $name = $org->name;
287         my $email = $org->email;
288         my $phone = $org->phone;
289
290         my( $s1, $s2, $city, $state, $zip );
291         my $baddr = $org->billing_address || $org->mailing_address;
292         if( $baddr ) {
293                 $s1             = $baddr->street1;
294                 $s2             = $baddr->street2;
295                 $city           = $baddr->city;
296                 $state  = $baddr->state;
297                 $zip            = $baddr->post_code;
298         }
299
300         $name  = entityize($name);
301         $phone = entityize($phone);
302         $s1      = entityize($s1);
303         $s2      = entityize($s2);
304         $city  = entityize($city);
305         $state = entityize($state);
306         $zip     = entityize($zip);
307         $email = entityize($email);
308
309         return ( $org, $name, $phone, $s1, $s2, $city, $state, $zip, $email );
310 }
311
312
313 sub print_org_xml_chunk {
314         my( $org, $name, $phone, $s1, $s2, $city, $state, $zip, $email ) = @_;
315         print <<"       XML";
316                         <library>
317                                 <libname>$name</libname>
318                                 <libphone>$phone</libphone>
319                                 <libstreet1>$s1 $s2</libstreet1>
320                                 <libcity_state_zip>$city, $state $zip</libcity_state_zip>
321                         </library>
322         XML
323 }
324
325
326 sub fetch_circ_data {
327         my $circ = shift;
328
329         my $title;
330         my $author;
331         my $cn;
332
333         my $d = $circ->due_date;
334         $d =~ s/[T ].*//og; # just for logging
335         $logger->debug("OD_notice:   processing circ ".$circ->id." $d");
336
337         my $due = DateTime::Format::ISO8601->new->parse_datetime(
338                 clense_ISO8601($circ->due_date));
339
340         my $day  = $due->day;
341         my $mon  = $due->month;
342         my $year = $due->year;
343
344         my $copy = $e->retrieve_asset_copy($circ->target_copy)
345                 or return handle_event($e->event);
346
347         my $bc = $copy->barcode;
348
349         if( $copy->call_number == OILS_PRECAT_CALL_NUMBER ) {
350                 $title = $copy->dummy_title || "";
351                 $author = $copy->dummy_author || "";
352
353         } else {
354
355                 my $volume = $e->retrieve_asset_call_number(
356                         [
357                                 $copy->call_number,
358                                 {
359                                         flesh => 1,
360                                         flesh_fields => {
361                                                 acn => [ qw/record/ ]
362                                         }
363                                 }
364                         ]
365                 ) or return handle_event($e->event);
366
367                 $cn = $volume->label;
368                 my $mods = $apputils->record_to_mvr($volume->record);
369                 if( $mods ) {
370                         $title = $mods->title || "";
371                         $author = $mods->author || "";
372                 }
373         }
374
375         $title = entityize($title);
376         $author = entityize($author);
377         $cn = entityize($cn);
378         $bc = entityize($bc);
379
380         return( $title, $author, $cn, $bc, $day, $mon, $year );
381 }
382
383
384 sub print_circ_chunk {
385         my $circ = shift;
386         my ( $title, $author, $cn, $bc, $day, $mon, $year ) = fetch_circ_data($circ);
387         my $cid = $circ->id;
388         print <<"       XML";
389                         <item>
390                                 <title>$title</title>
391                                 <author>$author</author>
392                                 <duedate>$mon/$day/$year</duedate>
393                                 <callno>$cn</callno>
394                                 <barcode>$bc</barcode>
395                                 <circ_id>$cid</circ_id>
396                         </item>
397         XML
398 }
399
400
401
402 sub send_email {
403         my( $range, $patron_data, $org_data, $circs ) = @_;
404         my( $org, $org_name, $org_phone, $org_s1, $org_s2, $org_city, $org_state, $org_zip, $org_email ) = @$org_data;
405         my( $patron, $bc, $fn, $mn, $ln, $user_s1, $user_s2, $user_city, $user_state, $user_zip ) = @$patron_data;
406
407         return unless $SEND_EMAILS;
408
409         my $pemail = $patron_data->[0]->email;
410
411         my $tmpl = $email_template;
412         my @time = localtime;
413         my $year = $time[5] + 1900;
414         my $mon  = $time[4] + 1;
415         my $day  = $time[3];
416
417         my $r = ($range eq '7day') ? 7 : 14;
418
419         $org_email ||= $mail_sender;
420
421         $tmpl =~ s/\${EMAIL_RECIPIENT}/$pemail/;
422         $tmpl =~ s/\${EMAIL_SENDER}/$mail_sender/o;
423         $tmpl =~ s/\${EMAIL_REPLY_TO}/$org_email/;
424    $tmpl =~ s/\${EMAIL_HEADERS}//;
425
426    $tmpl =~ s/\${RANGE}/$r/;
427    $tmpl =~ s/\${DATE}/$day\/$mon\/$year/;
428    $tmpl =~ s/\${FIRST_NAME}/$fn/;
429    $tmpl =~ s/\${MIDDLE_NAME}/$mn/;
430    $tmpl =~ s/\${LAST_NAME}/$ln/;
431
432         my ($itmpl) = $tmpl =~ /\${OVERDUE_ITEMS\[(.*)\]}/ms;
433
434         my $items = '';
435         for my $circ (@$circs) {
436                 my $circtmpl = $itmpl;
437                 my ( $title, $author, $cn, $bc, $due_day, $due_mon, $due_year ) = fetch_circ_data($circ);
438                 $circtmpl =~ s/\${TITLE}/$title/o;
439                 $circtmpl =~ s/\${AUTHOR}/$author/o;
440                 $circtmpl =~ s/\${CALL_NUMBER}/$cn/o;
441                 $circtmpl =~ s/\${DUE_DAY}/$due_day/o;
442                 $circtmpl =~ s/\${DUE_MONTH}/$due_mon/o;
443                 $circtmpl =~ s/\${DUE_YEAR}/$due_year/o;
444                 $circtmpl =~ s/\${ITEM_BARCODE}/$bc/o;
445                 $items .= "$circtmpl\n";
446         }
447
448         $tmpl =~ s/\${OVERDUE_ITEMS\[.*\]}/$items/ms;
449
450         my $org_addr = "$org_s1 $org_s2 $org_city, $org_state $org_zip";
451         $tmpl =~ s/\${ORG_NAME}/$org_name/o;
452         $tmpl =~ s/\${ORG_ADDRESS}/$org_addr/o;
453         $tmpl =~ s/\${ORG_PHONE}/$org_phone/o;
454
455         $logger->debug("OD_notice: sending email to $pemail: $tmpl");
456
457         my $sender = Email::Send->new({mailer => 'SMTP'});
458         $sender->mailer_args([Host => $smtp]);
459
460         my $stat = $sender->send($tmpl);
461
462         if( $stat and $stat->type eq 'success' ) {
463                 $logger->info("OD_notice:   successfully sent overdue email");
464         } else {
465                 $logger->warn("OD_notice:   unable to send hold overdue email: ".Dumper($stat));
466         }
467
468         $logger->info("OD_notice:   sending email to".$patron_data->[0]->email);
469 }
470
471 sub handle_event {
472         my $evt = shift;
473         warn "OD_notice: ".Dumper($evt) . "\n";
474         $logger->error("OD_notice: ".Dumper($evt));
475 }
476
477
478 sub entityize {
479         my $stuff = shift || return "";
480         $stuff =~ s/\</&lt;/og;
481         $stuff =~ s/\>/&gt;/og;
482         $stuff =~ s/\&/&amp;/og;
483         $stuff = NFC($stuff);
484         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
485         return $stuff;
486 }
487
488
489
490