Bug 12923 Improve error logging for advance_notices.pl
[koha.git] / misc / cronjobs / advance_notices.pl
1 #!/usr/bin/perl
2
3 # Copyright 2008 LibLime
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 =head1 NAME
21
22 advance_notices.pl - cron script to put item due reminders into message queue
23
24 =head1 SYNOPSIS
25
26 ./advance_notices.pl -c
27
28 or, in crontab:
29 0 1 * * * advance_notices.pl -c
30
31 =head1 DESCRIPTION
32
33 This script prepares pre-due and item due reminders to be sent to
34 patrons. It queues them in the message queue, which is processed by
35 the process_message_queue.pl cronjob. The type and timing of the
36 messages can be configured by the patrons in their "My Alerts" tab in
37 the OPAC.
38
39 =cut
40
41 use strict;
42 use warnings;
43 use Getopt::Long;
44 use Pod::Usage;
45 use Data::Dumper;
46 BEGIN {
47     # find Koha's Perl modules
48     # test carefully before changing this
49     use FindBin;
50     eval { require "$FindBin::Bin/../kohalib.pl" };
51 }
52 use C4::Biblio;
53 use C4::Context;
54 use C4::Letters;
55 use C4::Members;
56 use C4::Members::Messaging;
57 use C4::Overdues;
58 use Koha::DateUtils;
59 use C4::Log;
60
61 =head1 NAME
62
63 advance_notices.pl - prepare messages to be sent to patrons for nearly due, or due, items
64
65 =head1 SYNOPSIS
66
67 advance_notices.pl
68   [ -n ][ -m <number of days> ][ --itemscontent <comma separated field list> ][ -c ]
69
70 =head1 OPTIONS
71
72 =over 8
73
74 =item B<--help>
75
76 Print a brief help message and exits.
77
78 =item B<--man>
79
80 Prints the manual page and exits.
81
82 =item B<-v>
83
84 Verbose. Without this flag set, only fatal errors are reported.
85
86 =item B<-n>
87
88 Do not send any email. Advanced or due notices that would have been sent to
89 the patrons are printed to standard out.
90
91 =item B<-m>
92
93 Defines the maximum number of days in advance to send advance notices.
94
95 =item B<-c>
96
97 Confirm flag: Add this option. The script will only print a usage
98 statement otherwise.
99
100 =item B<--itemscontent>
101
102 comma separated list of fields that get substituted into templates in
103 places of the E<lt>E<lt>items.contentE<gt>E<gt> placeholder. This
104 defaults to due date,title,author,barcode
105
106 Other possible values come from fields in the biblios, items and
107 issues tables.
108
109 =back
110
111 =head1 DESCRIPTION
112
113 This script is designed to alert patrons when items are due, or coming due
114
115 =head2 Configuration
116
117 This script pays attention to the advanced notice configuration
118 performed by borrowers in the OPAC, or by staff in the patron detail page of the intranet. The content of the messages is configured in Tools -> Notices and slips. Advanced notices use the PREDUE template, due notices use DUE. More information about the use of this
119 section of Koha is available in the Koha manual.
120
121 =head2 Outgoing emails
122
123 Typically, messages are prepared for each patron with due
124 items, and who have selected (or the library has elected for them) Advance or Due notices.
125
126 These emails are staged in the outgoing message queue, as are messages
127 produced by other features of Koha. This message queue must be
128 processed regularly by the
129 F<misc/cronjobs/process_message_queue.pl> program.
130
131 In the event that the C<-n> flag is passed to this program, no emails
132 are sent. Instead, messages are sent on standard output from this
133 program. They may be redirected to a file if desired.
134
135 =head2 Templates
136
137 Templates can contain variables enclosed in double angle brackets like
138 E<lt>E<lt>thisE<gt>E<gt>. Those variables will be replaced with values
139 specific to the overdue items or relevant patron. Available variables
140 are:
141
142 =over
143
144 =item E<lt>E<lt>items.contentE<gt>E<gt>
145
146 one line for each item, each line containing a tab separated list of
147 title, author, barcode, issuedate
148
149 =item E<lt>E<lt>borrowers.*E<gt>E<gt>
150
151 any field from the borrowers table
152
153 =item E<lt>E<lt>branches.*E<gt>E<gt>
154
155 any field from the branches table
156
157 =back
158
159 =head1 SEE ALSO
160
161 The F<misc/cronjobs/overdue_notices.pl> program allows you to send
162 messages to patrons when their messages are overdue.
163 =cut
164
165 binmode( STDOUT, ':encoding(UTF-8)' );
166
167 # These are defaults for command line options.
168 my $confirm;                                                        # -c: Confirm that the user has read and configured this script.
169 my $nomail;                                                         # -n: No mail. Will not send any emails.
170 my $mindays     = 0;                                                # -m: Maximum number of days in advance to send notices
171 my $maxdays     = 30;                                               # -e: the End of the time period
172 my $verbose     = 0;                                                # -v: verbose
173 my $itemscontent = join(',',qw( date_due title author barcode ));
174
175 my $help    = 0;
176 my $man     = 0;
177
178 GetOptions(
179             'help|?'         => \$help,
180             'man'            => \$man,
181             'c'              => \$confirm,
182             'n'              => \$nomail,
183             'm:i'            => \$maxdays,
184             'v'              => \$verbose,
185             'itemscontent=s' => \$itemscontent,
186        )or pod2usage(2);
187 pod2usage(1) if $help;
188 pod2usage( -verbose => 2 ) if $man;;
189
190 # Since advance notice options are not visible in the web-interface
191 # unless EnhancedMessagingPreferences is on, let the user know that
192 # this script probably isn't going to do much
193 if ( ! C4::Context->preference('EnhancedMessagingPreferences') ) {
194     warn <<'END_WARN';
195
196 The "EnhancedMessagingPreferences" syspref is off.
197 Therefore, it is unlikely that this script will actually produce any messages to be sent.
198 To change this, edit the "EnhancedMessagingPreferences" syspref.
199
200 END_WARN
201 }
202 unless ($confirm) {
203      pod2usage(1);
204 }
205
206 cronlogaction();
207
208 # The fields that will be substituted into <<items.content>>
209 my @item_content_fields = split(/,/,$itemscontent);
210
211 warn 'getting upcoming due issues' if $verbose;
212 my $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $maxdays } );
213 warn 'found ' . scalar( @$upcoming_dues ) . ' issues' if $verbose;
214
215 # hash of borrowernumber to number of items upcoming
216 # for patrons wishing digests only.
217 my $upcoming_digest;
218 my $due_digest;
219
220 my $dbh = C4::Context->dbh();
221 my $sth = $dbh->prepare(<<'END_SQL');
222 SELECT biblio.*, items.*, issues.*
223   FROM issues,items,biblio
224   WHERE items.itemnumber=issues.itemnumber
225     AND biblio.biblionumber=items.biblionumber
226     AND issues.borrowernumber = ?
227     AND issues.itemnumber = ?
228     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
229 END_SQL
230
231 my $admin_adress = C4::Context->preference('KohaAdminEmailAddress');
232
233 my @letters;
234 UPCOMINGITEM: foreach my $upcoming ( @$upcoming_dues ) {
235     @letters = ();
236     warn 'examining ' . $upcoming->{'itemnumber'} . ' upcoming due items' if $verbose;
237
238     my $from_address = $upcoming->{branchemail} || $admin_adress;
239
240     my $borrower_preferences;
241     if ( 0 == $upcoming->{'days_until_due'} ) {
242         # This item is due today. Send an 'item due' message.
243         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
244                                                                                    message_name   => 'item_due' } );
245         next unless $borrower_preferences;
246         
247         if ( $borrower_preferences->{'wants_digest'} ) {
248             # cache this one to process after we've run through all of the items.
249             $due_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
250             $due_digest->{ $upcoming->{borrowernumber} }->{count}++;
251         } else {
252             my $biblio = C4::Biblio::GetBiblioFromItemNumber( $upcoming->{'itemnumber'} );
253             my $letter_type = 'DUE';
254             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},'0');
255             my $titles = "";
256             while ( my $item_info = $sth->fetchrow_hashref()) {
257               my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
258               $titles .= join("\t",@item_info) . "\n";
259             }
260
261             ## Get branch info for borrowers home library.
262             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
263                 my $letter = parse_letter( { letter_code    => $letter_type,
264                                       borrowernumber => $upcoming->{'borrowernumber'},
265                                       branchcode     => $upcoming->{'branchcode'},
266                                       biblionumber   => $biblio->{'biblionumber'},
267                                       itemnumber     => $upcoming->{'itemnumber'},
268                                       substitute     => { 'items.content' => $titles },
269                                       message_transport_type => $transport,
270                                     } )
271                     or warn "no letter of type '$letter_type' found for borrowernumber ".$upcoming->{'borrowernumber'}.". Please see sample_notices.sql";
272                 push @letters, $letter if $letter;
273             }
274         }
275     } else {
276         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
277                                                                                    message_name   => 'advance_notice' } );
278         next UPCOMINGITEM unless $borrower_preferences && exists $borrower_preferences->{'days_in_advance'};
279         next UPCOMINGITEM unless $borrower_preferences->{'days_in_advance'} == $upcoming->{'days_until_due'};
280
281         if ( $borrower_preferences->{'wants_digest'} ) {
282             # cache this one to process after we've run through all of the items.
283             $upcoming_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
284             $upcoming_digest->{ $upcoming->{borrowernumber} }->{count}++;
285         } else {
286             my $biblio = C4::Biblio::GetBiblioFromItemNumber( $upcoming->{'itemnumber'} );
287             my $letter_type = 'PREDUE';
288             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},$borrower_preferences->{'days_in_advance'});
289             my $titles = "";
290             while ( my $item_info = $sth->fetchrow_hashref()) {
291               my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
292               $titles .= join("\t",@item_info) . "\n";
293             }
294
295             ## Get branch info for borrowers home library.
296             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
297                 my $letter = parse_letter( { letter_code    => $letter_type,
298                                       borrowernumber => $upcoming->{'borrowernumber'},
299                                       branchcode     => $upcoming->{'branchcode'},
300                                       biblionumber   => $biblio->{'biblionumber'},
301                                       itemnumber     => $upcoming->{'itemnumber'},
302                                       substitute     => { 'items.content' => $titles },
303                                       message_transport_type => $transport,
304                                     } )
305                     or warn "no letter of type '$letter_type' found for borrowernumber ".$upcoming->{'borrowernumber'}.". Please see sample_notices.sql";
306                 push @letters, $letter if $letter;
307             }
308         }
309     }
310
311     # If we have prepared a letter, send it.
312     if ( @letters ) {
313       if ($nomail) {
314         for my $letter ( @letters ) {
315             local $, = "\f";
316             print $letter->{'content'};
317         }
318       }
319       else {
320         for my $letter ( @letters ) {
321             C4::Letters::EnqueueLetter( { letter                 => $letter,
322                                           borrowernumber         => $upcoming->{'borrowernumber'},
323                                           from_address           => $from_address,
324                                           message_transport_type => $letter->{message_transport_type} } );
325         }
326       }
327     }
328 }
329
330
331
332 # Now, run through all the people that want digests and send them
333
334 $sth = $dbh->prepare(<<'END_SQL');
335 SELECT biblio.*, items.*, issues.*
336   FROM issues,items,biblio
337   WHERE items.itemnumber=issues.itemnumber
338     AND biblio.biblionumber=items.biblionumber
339     AND issues.borrowernumber = ?
340     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
341 END_SQL
342 PATRON: while ( my ( $borrowernumber, $digest ) = each %$upcoming_digest ) {
343     @letters = ();
344     my $count = $digest->{count};
345     my $from_address = $digest->{email};
346
347     my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $borrowernumber,
348                                                                                   message_name   => 'advance_notice' } );
349     next PATRON unless $borrower_preferences; # how could this happen?
350
351
352     my $letter_type = 'PREDUEDGST';
353
354     $sth->execute($borrowernumber,$borrower_preferences->{'days_in_advance'});
355     my $titles = "";
356     while ( my $item_info = $sth->fetchrow_hashref()) {
357       my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
358       $titles .= join("\t",@item_info) . "\n";
359     }
360
361     ## Get branch info for borrowers home library.
362     my %branch_info = get_branch_info( $borrowernumber );
363
364     foreach my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
365         my $letter = parse_letter(
366             {
367                 letter_code    => $letter_type,
368                 borrowernumber => $borrowernumber,
369                 substitute     => {
370                     count           => $count,
371                     'items.content' => $titles,
372                     %branch_info,
373                 },
374                 branchcode             => $branch_info{"branches.branchcode"},
375                 message_transport_type => $transport,
376             }
377           )
378           or warn "no letter of type '$letter_type' found for borrowernumber $borrowernumber. Please see sample_notices.sql";
379         push @letters, $letter if $letter;
380     }
381
382     if ( @letters ) {
383       if ($nomail) {
384         for my $letter ( @letters ) {
385             local $, = "\f";
386             print $letter->{'content'};
387         }
388       }
389       else {
390         for my $letter ( @letters ) {
391             C4::Letters::EnqueueLetter( { letter                 => $letter,
392                                           borrowernumber         => $borrowernumber,
393                                           from_address           => $from_address,
394                                           message_transport_type => $letter->{message_transport_type} } );
395         }
396       }
397     }
398 }
399
400 # Now, run through all the people that want digests and send them
401 PATRON: while ( my ( $borrowernumber, $digest ) = each %$due_digest ) {
402     @letters = ();
403     my $count = $digest->{count};
404     my $from_address = $digest->{email};
405
406     my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $borrowernumber,
407                                                                                   message_name   => 'item_due' } );
408     next PATRON unless $borrower_preferences; # how could this happen?
409
410     my $letter_type = 'DUEDGST';
411     $sth->execute($borrowernumber,'0');
412     my $titles = "";
413     while ( my $item_info = $sth->fetchrow_hashref()) {
414       my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
415       $titles .= join("\t",@item_info) . "\n";
416     }
417
418     ## Get branch info for borrowers home library.
419     my %branch_info = get_branch_info( $borrowernumber );
420
421     for my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
422         my $letter = parse_letter(
423             {
424                 letter_code    => $letter_type,
425                 borrowernumber => $borrowernumber,
426                 substitute     => {
427                     count           => $count,
428                     'items.content' => $titles,
429                     %branch_info,
430                 },
431                 branchcode             => $branch_info{"branches.branchcode"},
432                 message_transport_type => $transport,
433             }
434           )
435           or warn "no letter of type '$letter_type' found for borrowernumber $borrowernumber. Please see sample_notices.sql";
436         push @letters, $letter if $letter;
437     }
438
439     if ( @letters ) {
440       if ($nomail) {
441         for my $letter ( @letters ) {
442             local $, = "\f";
443             print $letter->{'content'};
444         }
445       }
446       else {
447         for my $letter ( @letters ) {
448             C4::Letters::EnqueueLetter( { letter                 => $letter,
449                                           borrowernumber         => $borrowernumber,
450                                           from_address           => $from_address,
451                                           message_transport_type => $letter->{message_transport_type} } );
452         }
453       }
454     }
455
456 }
457
458 =head1 METHODS
459
460 =head2 parse_letter
461
462 =cut
463
464 sub parse_letter {
465     my $params = shift;
466     foreach my $required ( qw( letter_code borrowernumber ) ) {
467         return unless exists $params->{$required};
468     }
469
470     my %table_params = ( 'borrowers' => $params->{'borrowernumber'} );
471
472     if ( my $p = $params->{'branchcode'} ) {
473         $table_params{'branches'} = $p;
474     }
475     if ( my $p = $params->{'itemnumber'} ) {
476         $table_params{'issues'} = $p;
477         $table_params{'items'} = $p;
478     }
479     if ( my $p = $params->{'biblionumber'} ) {
480         $table_params{'biblio'} = $p;
481         $table_params{'biblioitems'} = $p;
482     }
483
484     return C4::Letters::GetPreparedLetter (
485         module => 'circulation',
486         letter_code => $params->{'letter_code'},
487         branchcode => $table_params{'branches'},
488         substitute => $params->{'substitute'},
489         tables     => \%table_params,
490         message_transport_type => $params->{message_transport_type},
491     );
492 }
493
494 sub format_date {
495     my $date_string = shift;
496     my $dt=dt_from_string($date_string);
497     return output_pref($dt);
498 }
499
500 =head2 get_branch_info
501
502 =cut
503
504 sub get_branch_info {
505     my ( $borrowernumber ) = @_;
506
507     ## Get branch info for borrowers home library.
508     my $borrower_details = C4::Members::GetMember( borrowernumber => $borrowernumber );
509     my $borrower_branchcode = $borrower_details->{'branchcode'};
510     my $branch = C4::Branch::GetBranchDetail( $borrower_branchcode );
511     my %branch_info;
512     foreach my $key( keys %$branch ) {
513         $branch_info{"branches.$key"} = $branch->{$key};
514     }
515
516     return %branch_info;
517 }
518
519 1;
520
521 __END__