]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/support-scripts/generate_circ_notices.pl
safer MR mapping
[Evergreen.git] / Open-ILS / src / support-scripts / generate_circ_notices.pl
1 #!/usr/bin/perl
2 # ---------------------------------------------------------------
3 # Copyright (C) 2008  Georgia Public Library Service
4 # Bill Erickson <erickson@esilibrary.com>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #  ---------------------------------------------------------------
16 use strict; use warnings;
17 require 'oils_header.pl';
18 use vars qw/$logger/;
19 use DateTime;
20 use Template;
21 use Data::Dumper;
22 use Email::Send;
23 use Getopt::Long;
24 use Unicode::Normalize;
25 use DateTime::Format::ISO8601;
26 use OpenSRF::Utils qw/:datetime/;
27 use OpenSRF::Utils::JSON;
28 use OpenSRF::Utils::SettingsClient;
29 use OpenSRF::AppSession;
30 use OpenILS::Const qw/:const/;
31 use OpenILS::Application::AppUtils;
32 use OpenILS::Const qw/:const/;
33 my $U = 'OpenILS::Application::AppUtils';
34
35 my $settings = undef;
36 my $e = OpenILS::Utils::CStoreEditor->new;
37
38 my @global_overdue_circs; # all circ collections stored here go into the final global XML file
39
40 # - set up default values
41 my $opt_osrf_config = '/openils/conf/opensrf_core.xml';
42 my $opt_send_email = 0;
43 my $opt_gen_day_intervals = 0;
44 my $opt_days_back = '';
45 my $opt_gen_global_templates = 0;
46 my $opt_show_help = 0;
47 my $opt_append_global_email_fail;
48 my $opt_notice_types = '';
49 my $opt_use_email_outfile;
50 my $opt_use_email_recipient;
51
52 GetOptions(
53     'osrf_config=s' => \$opt_osrf_config,
54     'send-email' => \$opt_send_email,
55     'generate-day-intervals' => \$opt_gen_day_intervals,
56     'generate-global-templates' => \$opt_gen_global_templates,
57     'days-back=s' => \$opt_days_back,
58     'append-global-email-fail' => \$opt_append_global_email_fail,
59     'notice-types=s' => \$opt_notice_types,
60     'use-email-outfile=s' => \$opt_use_email_outfile,
61     'use-email-recipient=s' => \$opt_use_email_recipient,
62     'help' => \$opt_show_help,
63 );
64
65 help() and exit if $opt_show_help;
66
67 sub help {
68     print <<HELP;
69
70 Evergreen Circulation Notice Generator
71
72     ---osrf_config <config_file>
73     
74     --send-email
75         If set, generate email notices
76
77     --use-email-outfile <file>
78         Instead of sending emails, append each email (complete with headers) to this file
79
80     --use-email-recipient <user\@example.com>
81         Send all email notices to this user instead of the patron.  This updates the 
82         email address on the user object attached to the circulations, so no 
83         change to the email templates is required.
84
85     --generate-day-intervals
86         If set, notices which have a notify_interval of >= 1 day will be processed.
87
88     --generate-global-templates
89         Collect all non-emailed notices into a global set and generate templates based on that set.
90
91     --append-global-email-fail
92         If an attempt was made to send an email notice but it failed, the notice is appended
93         to the global notice file set.  This will only have any bearing if --generate-global-templates
94         is enabled.
95
96     --days-back <days_back_comma_separted>  
97         This is used to set the effective run date of the script.
98         This is useful if you don't want to generate notices on certain days.  For example, if you don't 
99         generate notices on the weekend, you would run this script on weekdays and set --days-back to 
100         0,1,2 when it's run on Monday to capture any notices from Saturday and Sunday. 
101
102     --notice-types <overdue,predue,...>
103         Comma-separated list of notice types to generate for this run of the script
104
105     --help 
106         Print this help message
107 HELP
108 }
109
110
111 sub main {
112     osrf_connect($opt_osrf_config);
113     $settings = OpenSRF::Utils::SettingsClient->new;
114
115     die "Please specify at least 1 type of notice to generate with --notice-types\n"
116         unless $opt_notice_types;
117
118     unlink $opt_use_email_outfile if $opt_use_email_outfile;
119
120     my $sender_address = $settings->config_value(notifications => 'sender_address');
121     my $od_sender_addr = $settings->config_value(notifications => overdue => 'sender_address') || $sender_address;
122     my $pd_sender_addr = $settings->config_value(notifications => predue => 'sender_address') || $sender_address;
123     my $overdue_notices = $settings->config_value(notifications => overdue => 'notice');
124     my $predue_notices = $settings->config_value(notifications => predue => 'notice');
125
126     $overdue_notices = [$overdue_notices] unless ref $overdue_notices eq 'ARRAY'; 
127     $predue_notices = [$predue_notices] unless ref $predue_notices eq 'ARRAY'; 
128
129     my @overdues = sort { 
130         OpenSRF::Utils->interval_to_seconds($a->{notify_interval}) <=> 
131         OpenSRF::Utils->interval_to_seconds($b->{notify_interval}) } @$overdue_notices;
132
133     my @predues = sort { 
134         OpenSRF::Utils->interval_to_seconds($a->{notify_interval}) <=> 
135         OpenSRF::Utils->interval_to_seconds($b->{notify_interval}) } @$predue_notices;
136
137     for my $db (($opt_days_back) ? split(',', $opt_days_back) : 0) {
138         if($opt_notice_types =~ /overdue/) {
139             generate_notice_set($_, 'overdue', $db) for @overdues;
140         }
141         if($opt_notice_types =~ /predue/) {
142             generate_notice_set($_, 'predue', $db) for @predues;
143         }
144     }
145
146     generate_global_overdue_file() if $opt_gen_global_templates;
147 }
148
149 sub generate_global_overdue_file {
150     $logger->info("notice: processing ".scalar(@global_overdue_circs)." for global template");
151     return unless @global_overdue_circs;
152
153     my $tt = Template->new({ABSOLUTE => 1});
154
155     $tt->process(
156         $settings->config_value(notifications => overdue => 'combined_template'),
157         {
158             overdues => \@global_overdue_circs,
159             get_bib_attr => \&get_bib_attr,
160             parse_due_date => \&parse_due_date, # let the templates decide date format
161             escape_xml => \&escape_xml,
162         }, 
163         \&global_overdue_output
164     ) or $logger->error('notice: Template error '.$tt->error);
165 }
166
167 sub global_overdue_output {
168     binmode STDOUT, ":utf8";
169     print shift();
170 }
171
172
173 sub generate_notice_set {
174     my($notice, $type, $days_back) = @_;
175
176     my $notify_interval = OpenSRF::Utils->interval_to_seconds($notice->{notify_interval});
177     $notify_interval = -$notify_interval if $type eq 'overdue';
178
179     my ($start_date, $end_date) = make_date_range($notify_interval - $days_back * 86400);
180
181     $logger->info("notice: retrieving circs with due date in range $start_date -> $end_date");
182
183     my $QUERY = {
184         select => {
185             circ => ['id']
186         }, 
187         from => 'circ', 
188         where => {
189             '+circ' => {
190                 checkin_time => undef, 
191                 '-or' => [
192                     {stop_fines => {'not in' => ["LOST","LONGOVERDUE","CLAIMSRETURNED"]}},
193                     {stop_fines => undef}
194                 ],
195                                 due_date => {between => [$start_date, $end_date]}
196             }
197         },
198         order_by => {circ => ['usr', 'circ_lib']}
199     };
200
201     # if a circ duration is defined for this type of notice
202     if(my $durs = $notice->{circ_duration_range}) {
203         $QUERY->{where}->{'+circ'}->{duration} = {between => [$durs->{from}, $durs->{to}]};
204     }
205
206     my $circs = $e->json_query($QUERY, {timeout => 18000, substream => 1});
207     process_circs($notice, $type, map {$_->{id}} @$circs);
208 }
209
210
211 sub process_circs {
212     my $notice = shift;
213     my $type = shift;
214     my @circs = @_;
215
216         return unless @circs;
217
218         $logger->info("notice: processing $type notices with notify interval ". 
219         $notice->{notify_interval}."  and ".scalar(@circs)." circs");
220
221         my $org; 
222         my $patron;
223         my @current;
224
225         my $x = 0;
226         for my $circ (@circs) {
227                 $circ = $e->retrieve_action_circulation($circ);
228
229                 if( !defined $org or 
230                                 $circ->circ_lib != $org  or $circ->usr ne $patron ) {
231                         $org = $circ->circ_lib;
232                         $patron = $circ->usr;
233                         generate_notice($notice, $type, @current) if @current;
234                         @current = ();
235                 }
236
237                 push(@current, $circ);
238                 $x++;
239         }
240
241         $logger->info("notice: processed $x circs");
242         generate_notice($notice, $type, @current);
243 }
244
245 my %ORG_CACHE;
246 my %ORG_FROM_CACHE;
247
248 sub get_from_addr {
249     my $type = shift;
250     my $org_id = shift;
251     my $sender;
252
253     if(defined $ORG_FROM_CACHE{$org_id}) {
254         # we have we already loaded the setting for this org unit
255                 $sender = $ORG_FROM_CACHE{$org_id};
256
257     } elsif(my $set = $e->search_actor_org_unit_setting( 
258                         {name => 'org.bounced_emails', org_unit => $org_id} )->[0]) {
259                 my $bemail = OpenSRF::Utils::JSON->JSON2perl($set->value);
260                 $sender = $ORG_FROM_CACHE{$org_id} = $bemail if $bemail;
261         }
262
263     unless($sender) {
264         # there is no setting, use the configured sender
265         $sender = $settings->config_value(
266             notifications => $type => 'sender_address') || 
267             $settings->config_value(notifications => 'sender_address');
268         $ORG_FROM_CACHE{$org_id} = '';
269     }
270
271     return $sender;
272 }
273
274 sub generate_notice {
275     my $notice = shift;
276     my $type = shift;
277     my @circs = @_;
278     return unless @circs;
279     my $circ_list = fetch_circ_data(@circs);
280     my $tt = Template->new({ABSOLUTE => 1});
281
282     # see if there is a configured bounce address for this org unit.
283     # if so, use that as the sender
284     my $org_id = $circ_list->[0]->circ_lib->id;
285     my $sender = get_from_addr($type, $org_id);
286
287     my $context = {   
288         circ_list => $circ_list,
289         get_bib_attr => \&get_bib_attr,
290         parse_due_date => \&parse_due_date, # let the templates decide date format
291         smtp_sender => $sender,
292         notice => $notice,
293     };
294
295     push(@global_overdue_circs, $context) if 
296         $type eq 'overdue' and $notice->{file_append} =~ /always/i;
297
298     if( ($opt_send_email or $opt_use_email_outfile) and 
299             $notice->{email_notify} and 
300             my $email = $circ_list->[0]->usr->email) {
301
302         if(my $tmpl = $notice->{email_template}) {
303             $tt->process($tmpl, $context, 
304                 sub { 
305                     handle_email_template_output($notice, $type, $context, $email, @_); 
306                 }
307             ) or $logger->error('notice: Template error '.$tt->error);
308         } 
309     } else {
310         push(@global_overdue_circs, $context) 
311             if $type eq 'overdue' and $notice->{file_append} =~ /noemail/i;
312     }
313 }
314
315 my $last_mvr;
316 sub get_bib_attr {
317     my $circ = shift;
318     my $attr = shift;
319     my $copy = $circ->target_copy;
320     if($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) {
321         return $copy->dummy_title || '' if $attr eq 'title';
322         return $copy->dummy_author || '' if $attr eq 'author';
323     } else {
324         $last_mvr = $U->record_to_mvr($copy->call_number->record)
325             unless $last_mvr and $last_mvr->doc_id == $copy->call_number->record->id;
326         return $last_mvr->title || '' if $attr eq 'title';
327         return $last_mvr->author || '' if $attr eq 'author';
328     }
329 }
330
331 # provides a date that Template::Plugin::Date can parse
332 sub parse_due_date {
333     my $circ = shift;
334     my $due = DateTime::Format::ISO8601->new->parse_datetime(clense_ISO8601($circ->due_date));
335     return sprintf(
336         "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
337         $due->hour,
338         $due->minute,
339         $due->second,
340         $due->day,
341         $due->month,
342         $due->year
343     );
344 }
345
346 sub escape_xml {
347     my $str = shift;
348     $str =~ s/&/&amp;/sog;
349     $str =~ s/</&lt;/sog;
350     $str =~ s/>/&gt;/sog;
351     return $str;
352 }
353
354
355 sub handle_email_template_output {
356     my $notice = shift;
357     my $type = shift;
358     my $context = shift;
359     my $email = shift;
360     my $msg = shift;
361
362     if($opt_use_email_outfile) {
363         if(open(F, ">>$opt_use_email_outfile")) {
364             binmode F, ":utf8";
365             $logger->debug("notice: appending emails to outfile $opt_use_email_outfile");
366             print F $msg;
367             close F;
368         } else {
369             $logger->error("notice: unable to open --use-email-outfile $opt_use_email_outfile for writing: $@");
370         }
371     }
372
373
374     if($opt_send_email) {
375             my $sender = Email::Send->new({mailer => 'SMTP'});
376         my $smtp_server = $settings->config_value(notifications => 'smtp_server');
377         $logger->debug("notice: smtp server is $smtp_server");
378             $sender->mailer_args([Host => $smtp_server]);
379             my $stat = $sender->send($msg);
380     
381             if( $stat and $stat->type eq 'success' ) {
382                     $logger->info("notice: successfully sent $type email to $email");
383             } else {
384                     $logger->warn("notice: unable to send $type email to $email: ".Dumper($stat));
385             # if we were unable to send the email, add this notice set to the global notify set
386             push(@global_overdue_circs, $context) 
387                 if $opt_append_global_email_fail and 
388                     $type eq 'overdue' and $notice->{file_append} =~ /noemail/i;
389             }
390     }
391 }
392
393 sub fetch_circ_data {
394     my @circs = @_;
395
396         my $circ_lib_id = $circs[0]->circ_lib;
397         my $usr_id = $circs[0]->usr;
398         $logger->debug("notice: printing user:$usr_id circ_lib:$circ_lib_id");
399
400     my $usr = $e->retrieve_actor_user([
401         $usr_id,
402         {   flesh => 1,
403             flesh_fields => {
404                 au => [qw/card billing_address mailing_address/] 
405             }
406         }
407     ]);
408
409     # if the caller has defined a test email recipient, override 
410     # the user's email if they have one.
411     $usr->email($opt_use_email_recipient) if $usr->email and $opt_use_email_recipient;
412
413     my $circ_lib = $ORG_CACHE{$circ_lib_id} ||
414         $e->retrieve_actor_org_unit([
415             $circ_lib_id,
416             {   flesh => 1,
417                 flesh_fields => {
418                     aou => [qw/billing_address mailing_address/],
419                 }
420             }
421         ]);
422     $ORG_CACHE{$circ_lib_id} = $circ_lib;
423
424     my $circ_objs = $e->search_action_circulation([
425         {id => [map {$_->id} @circs]},
426         {   flesh => 3,
427             flesh_fields => {
428                 circ => [q/target_copy/],
429                 acp => ['call_number'],
430                 acn => ['record'],
431             }
432         }
433     ]);
434
435     $_->circ_lib($circ_lib) for @$circ_objs;
436     $_->usr($usr) for @$circ_objs;
437
438     return $circ_objs
439 }
440
441
442 sub make_date_range {
443         my $offset = shift;
444     #my $is_day_precision = shift; # window?
445
446         my $epoch = CORE::time + $offset;
447         my $date = DateTime->from_epoch(epoch => $epoch, time_zone => 'local');
448
449         $date->set_hour(0);
450         $date->set_minute(0);
451         $date->set_second(0);
452         my $start = "$date";
453         
454         $date->set_hour(23);
455         $date->set_minute(59);
456         $date->set_second(59);
457
458         return ($start, "$date");
459 }
460
461 main();