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