]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/support-scripts/generate_circ_notices.pl
added logic for extracting title, author (and potentiall other attributes) from the...
[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 ($osrf_config, $send_email, $gen_day_intervals, $days_back) = 
39     ('/openils/conf/opensrf_core.xml', 1, 0, 0); 
40
41 GetOptions(
42     'osrf_osrf_config=s' => \$osrf_config,
43     'send-emails' => \$send_email,
44     'generate-day-intervals' => \$gen_day_intervals,
45     'days-back=s' => \$days_back,
46 );
47
48 sub help {
49     print <<HELP;
50         --config <config_file>
51         
52         --send-emails If set, generate email notices
53
54         --generate-day-intervals If set, notices which have a notify_interval of >= 1 day will be processed.
55
56         --days-back <days_back_comma_separted>  This is used to set the effective run date of the script.
57             This is useful if you don't want to generate notices on certain days.  For example, if you don't 
58             generate notices on the weekend, you would run this script on weekdays and set --days-back to 
59             0,1,2 when it's run on Monday to capture any notices from Saturday and Sunday. 
60 HELP
61 }
62
63
64 sub main {
65     osrf_connect($osrf_config);
66     $settings = OpenSRF::Utils::SettingsClient->new;
67
68     my $smtp_server = $settings->config_value(notifications => 'smtp_server');
69     my $sender_address = $settings->config_value(notifications => 'sender_address');
70     my $od_sender_addr = $settings->config_value(notifications => overdue => 'sender_address') || $sender_address;
71     my $pd_sender_addr = $settings->config_value(notifications => predue => 'sender_address') || $sender_address;
72     my $overdue_notices = $settings->config_value(notifications => overdue => 'notice');
73     my $predue_notices = $settings->config_value(notifications => predue => 'notice');
74
75     $overdue_notices = [$overdue_notices] unless ref $overdue_notices eq 'ARRAY'; 
76     $predue_notices = [$predue_notices] unless ref $predue_notices eq 'ARRAY'; 
77
78     my @overdues = sort { 
79         OpenSRF::Utils->interval_to_seconds($a->{notify_interval}) <=> 
80         OpenSRF::Utils->interval_to_seconds($b->{notify_interval}) } @$overdue_notices;
81
82     my @predues = sort { 
83         OpenSRF::Utils->interval_to_seconds($a->{notify_interval}) <=> 
84         OpenSRF::Utils->interval_to_seconds($b->{notify_interval}) } @$predue_notices;
85
86     generate_notice_set($_, 'overdue') for @overdues;
87     generate_notice_set($_, 'predue') for @predues;
88 }
89
90
91 sub generate_notice_set {
92     my($notice, $type) = @_;
93
94     my $notify_interval = OpenSRF::Utils->interval_to_seconds($notice->{notify_interval});
95     $notify_interval = -$notify_interval if $type eq 'overdue';
96
97     my ($start_date, $end_date) = make_date_range(-$days_back + $notify_interval);
98
99     $logger->info("notice: retrieving circs with due date in range $start_date -> $end_date");
100
101     my $QUERY = {
102         select => {
103             circ => ['id']
104         }, 
105         from => 'circ', 
106         where => {
107             '+circ' => {
108                 checkin_time => undef, 
109                 '-or' => [
110                     {stop_fines => ["LOST","LONGOVERDUE","CLAIMSRETURNED"]},
111                     {stop_fines => undef}
112                 ],
113                                 due_date => {between => [$start_date, $end_date]},
114             }
115         }
116     };
117
118     # if a circ duration is defined for this type of notice
119     if(my $durs = $settings->{circ_duration_range}) {
120         $QUERY->{where}->{'+circ'}->{duration} = {between => [$durs->{from}, $durs->{to}]};
121     }
122
123     my $circs = $e->json_query($QUERY, {timeout => 18000, substream => 1});
124     process_circs($notice, $type, map {$_->{id}} @$circs);
125 }
126
127
128 sub process_circs {
129     my $notice = shift;
130     my $type = shift;
131     my @circs = @_;
132
133         return unless @circs;
134
135         $logger->info("notice: processing $type notices with notify interval ". 
136         $notice->{notify_interval}."  and ".scalar(@circs)." circs");
137
138         my $org; 
139         my $patron;
140         my @current;
141
142         my $x = 0;
143         for my $circ (@circs) {
144                 $circ = $e->retrieve_action_circulation($circ);
145
146                 if( !defined $org or 
147                                 $circ->circ_lib != $org  or $circ->usr ne $patron ) {
148                         $org = $circ->circ_lib;
149                         $patron = $circ->usr;
150                         generate_notice($notice, $type, @current) if @current;
151                         @current = ();
152                 }
153
154                 push(@current, $circ);
155                 $x++;
156         }
157
158         $logger->info("notice: processed $x circs");
159         generate_notice($notice, $type, @current);
160 }
161
162 my %ORG_CACHE;
163
164 sub generate_notice {
165     my $notice = shift;
166     my $type = shift;
167     my @circs = @_;
168     return unless @circs;
169     my $circ_list = fetch_circ_data(@circs);
170     my $tt = Template->new({
171         ABSOLUTE => 1,
172     });
173
174     my $sender = $settings->config_value(
175         notifications => $type => 'sender_address') || 
176         $settings->config_value(notifications => 'sender_address');
177
178     $tt->process(
179         $notice->{template}, 
180         {   circ_list => $circ_list,
181             get_bib_attr => \&get_bib_attr,
182             parse_due_date => \&parse_due_date, # let the templates decide date format
183             smtp_sender => $sender,
184             smtp_repley => $sender # XXX
185         },
186         \&handle_template_output
187     ) or $logger->error('notice: Template error '.$tt->error);
188 }
189
190 sub get_bib_attr {
191     my $circ = shift;
192     my $attr = shift;
193     my $copy = $circ->target_copy;
194     if($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) {
195         return $copy->dummy_title || '' if $attr eq 'title';
196         return $copy->dummy_author || '' if $attr eq 'author';
197     } else {
198         my $mvr = $U->record_to_mvr($copy->call_number->record);
199         return $mvr->title || '' if $attr eq 'title';
200         return $mvr->author || '' if $attr eq 'author';
201     }
202 }
203
204 sub parse_due_date {
205     my $circ = shift;
206     my $due = DateTime::Format::ISO8601->new->parse_datetime(clense_ISO8601($circ->due_date));
207     my $info = {
208         year => $due->year, 
209         month => sprintf("%0.2d",$due->month), 
210         day => sprintf("%0.2d", $due->day)
211     };
212
213     # for day-based circulations, hour and minute are not relevant
214     return $info if (OpenSRF::Utils->interval_to_seconds($circ->duration) % 86400) == 0;
215
216     $info->{hour} = sprintf("%0.2d",$due->hour);  
217     $info->{minute} = sprintf("%0.2d",$due->minute);  
218     return $info;
219 }
220
221
222 sub handle_template_output {
223     my $str = shift;
224     print "$str\n";
225 }
226
227
228
229 sub fetch_circ_data {
230     my @circs = @_;
231
232         my $circ_lib_id = $circs[0]->circ_lib;
233         my $usr_id = $circs[0]->usr;
234         $logger->debug("notice: printing user:$usr_id circ_lib:$circ_lib_id");
235
236     my $usr = $e->retrieve_actor_user([
237         $usr_id,
238         {   flesh => 1,
239             flesh_fields => {
240                 au => [qw/card billing_address mailing_address/] 
241             }
242         }
243     ]);
244
245     my $circ_lib = $ORG_CACHE{$circ_lib_id} ||
246         $e->retrieve_actor_org_unit([
247             $circ_lib_id,
248             {   flesh => 1,
249                 flesh_fields => {
250                     aou => [qw/billing_address mailing_address/],
251                 }
252             }
253         ]);
254     $ORG_CACHE{$circ_lib_id} = $circ_lib;
255
256     my $circ_objs = $e->search_action_circulation([
257         {id => [map {$_->id} @circs]},
258         {   flesh => 3,
259             flesh_fields => {
260                 circ => [q/target_copy/],
261                 acp => ['call_number'],
262                 acn => ['record'],
263             }
264         }
265     ]);
266
267     $_->circ_lib($circ_lib) for @$circ_objs;
268     $_->usr($usr) for @$circ_objs;
269
270     return $circ_objs
271 }
272
273
274 sub make_date_range {
275         my $offset = shift;
276     #my $is_day_precision = shift; # window?
277
278         my $epoch = CORE::time + $offset;
279         my $date = DateTime->from_epoch(epoch => $epoch, time_zone => 'local');
280
281         $date->set_hour(0);
282         $date->set_minute(0);
283         $date->set_second(0);
284         my $start = "$date";
285         
286         $date->set_hour(23);
287         $date->set_minute(59);
288         $date->set_second(59);
289
290         return ($start, "$date");
291 }
292
293 main();