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