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