Bug 14910: Redirect to the circulation module after a renew
[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 # These are defaults for command line options.
166 my $confirm;                                                        # -c: Confirm that the user has read and configured this script.
167 my $nomail;                                                         # -n: No mail. Will not send any emails.
168 my $mindays     = 0;                                                # -m: Maximum number of days in advance to send notices
169 my $maxdays     = 30;                                               # -e: the End of the time period
170 my $verbose     = 0;                                                # -v: verbose
171 my $itemscontent = join(',',qw( date_due title author barcode ));
172
173 my $help    = 0;
174 my $man     = 0;
175
176 GetOptions(
177             'help|?'         => \$help,
178             'man'            => \$man,
179             'c'              => \$confirm,
180             'n'              => \$nomail,
181             'm:i'            => \$maxdays,
182             'v'              => \$verbose,
183             'itemscontent=s' => \$itemscontent,
184        )or pod2usage(2);
185 pod2usage(1) if $help;
186 pod2usage( -verbose => 2 ) if $man;;
187
188 # Since advance notice options are not visible in the web-interface
189 # unless EnhancedMessagingPreferences is on, let the user know that
190 # this script probably isn't going to do much
191 if ( ! C4::Context->preference('EnhancedMessagingPreferences') ) {
192     warn <<'END_WARN';
193
194 The "EnhancedMessagingPreferences" syspref is off.
195 Therefore, it is unlikely that this script will actually produce any messages to be sent.
196 To change this, edit the "EnhancedMessagingPreferences" syspref.
197
198 END_WARN
199 }
200 unless ($confirm) {
201      pod2usage(1);
202 }
203
204 cronlogaction();
205
206 # The fields that will be substituted into <<items.content>>
207 my @item_content_fields = split(/,/,$itemscontent);
208
209 warn 'getting upcoming due issues' if $verbose;
210 my $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $maxdays } );
211 warn 'found ' . scalar( @$upcoming_dues ) . ' issues' if $verbose;
212
213 # hash of borrowernumber to number of items upcoming
214 # for patrons wishing digests only.
215 my $upcoming_digest;
216 my $due_digest;
217
218 my $dbh = C4::Context->dbh();
219 my $sth = $dbh->prepare(<<'END_SQL');
220 SELECT biblio.*, items.*, issues.*
221   FROM issues,items,biblio
222   WHERE items.itemnumber=issues.itemnumber
223     AND biblio.biblionumber=items.biblionumber
224     AND issues.borrowernumber = ?
225     AND issues.itemnumber = ?
226     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
227 END_SQL
228
229 my $admin_adress = C4::Context->preference('KohaAdminEmailAddress');
230
231 my @letters;
232 UPCOMINGITEM: foreach my $upcoming ( @$upcoming_dues ) {
233     @letters = ();
234     warn 'examining ' . $upcoming->{'itemnumber'} . ' upcoming due items' if $verbose;
235
236     my $from_address = $upcoming->{branchemail} || $admin_adress;
237
238     my $borrower_preferences;
239     if ( 0 == $upcoming->{'days_until_due'} ) {
240         # This item is due today. Send an 'item due' message.
241         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
242                                                                                    message_name   => 'item_due' } );
243         next unless $borrower_preferences;
244         
245         if ( $borrower_preferences->{'wants_digest'} ) {
246             # cache this one to process after we've run through all of the items.
247             $due_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
248             $due_digest->{ $upcoming->{borrowernumber} }->{count}++;
249         } else {
250             my $biblio = C4::Biblio::GetBiblioFromItemNumber( $upcoming->{'itemnumber'} );
251             my $letter_type = 'DUE';
252             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},'0');
253             my $titles = "";
254             while ( my $item_info = $sth->fetchrow_hashref()) {
255               my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
256               $titles .= join("\t",@item_info) . "\n";
257             }
258
259             ## Get branch info for borrowers home library.
260             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
261                 my $letter = parse_letter( { letter_code    => $letter_type,
262                                       borrowernumber => $upcoming->{'borrowernumber'},
263                                       branchcode     => $upcoming->{'branchcode'},
264                                       biblionumber   => $biblio->{'biblionumber'},
265                                       itemnumber     => $upcoming->{'itemnumber'},
266                                       substitute     => { 'items.content' => $titles },
267                                       message_transport_type => $transport,
268                                     } )
269                     or warn "no letter of type '$letter_type' found. Please see sample_notices.sql";
270                 push @letters, $letter if $letter;
271             }
272         }
273     } else {
274         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
275                                                                                    message_name   => 'advance_notice' } );
276         next UPCOMINGITEM unless $borrower_preferences && exists $borrower_preferences->{'days_in_advance'};
277         next UPCOMINGITEM unless $borrower_preferences->{'days_in_advance'} == $upcoming->{'days_until_due'};
278
279         if ( $borrower_preferences->{'wants_digest'} ) {
280             # cache this one to process after we've run through all of the items.
281             $upcoming_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
282             $upcoming_digest->{ $upcoming->{borrowernumber} }->{count}++;
283         } else {
284             my $biblio = C4::Biblio::GetBiblioFromItemNumber( $upcoming->{'itemnumber'} );
285             my $letter_type = 'PREDUE';
286             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},$borrower_preferences->{'days_in_advance'});
287             my $titles = "";
288             while ( my $item_info = $sth->fetchrow_hashref()) {
289               my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
290               $titles .= join("\t",@item_info) . "\n";
291             }
292
293             ## Get branch info for borrowers home library.
294             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
295                 my $letter = parse_letter( { letter_code    => $letter_type,
296                                       borrowernumber => $upcoming->{'borrowernumber'},
297                                       branchcode     => $upcoming->{'branchcode'},
298                                       biblionumber   => $biblio->{'biblionumber'},
299                                       itemnumber     => $upcoming->{'itemnumber'},
300                                       substitute     => { 'items.content' => $titles },
301                                       message_transport_type => $transport,
302                                     } )
303                     or warn "no letter of type '$letter_type' found. Please see sample_notices.sql";
304                 push @letters, $letter if $letter;
305             }
306         }
307     }
308
309     # If we have prepared a letter, send it.
310     if ( @letters ) {
311       if ($nomail) {
312         for my $letter ( @letters ) {
313             local $, = "\f";
314             print $letter->{'content'};
315         }
316       }
317       else {
318         for my $letter ( @letters ) {
319             C4::Letters::EnqueueLetter( { letter                 => $letter,
320                                           borrowernumber         => $upcoming->{'borrowernumber'},
321                                           from_address           => $from_address,
322                                           message_transport_type => $letter->{message_transport_type} } );
323         }
324       }
325     }
326 }
327
328
329
330 # Now, run through all the people that want digests and send them
331
332 $sth = $dbh->prepare(<<'END_SQL');
333 SELECT biblio.*, items.*, issues.*
334   FROM issues,items,biblio
335   WHERE items.itemnumber=issues.itemnumber
336     AND biblio.biblionumber=items.biblionumber
337     AND issues.borrowernumber = ?
338     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
339 END_SQL
340 PATRON: while ( my ( $borrowernumber, $digest ) = each %$upcoming_digest ) {
341     @letters = ();
342     my $count = $digest->{count};
343     my $from_address = $digest->{email};
344
345     my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $borrowernumber,
346                                                                                   message_name   => 'advance_notice' } );
347     next PATRON unless $borrower_preferences; # how could this happen?
348
349
350     my $letter_type = 'PREDUEDGST';
351
352     $sth->execute($borrowernumber,$borrower_preferences->{'days_in_advance'});
353     my $titles = "";
354     while ( my $item_info = $sth->fetchrow_hashref()) {
355       my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
356       $titles .= join("\t",@item_info) . "\n";
357     }
358
359     ## Get branch info for borrowers home library.
360     my %branch_info = get_branch_info( $borrowernumber );
361
362     foreach my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
363         my $letter = parse_letter(
364             {
365                 letter_code    => $letter_type,
366                 borrowernumber => $borrowernumber,
367                 substitute     => {
368                     count           => $count,
369                     'items.content' => $titles,
370                     %branch_info,
371                 },
372                 branchcode             => $branch_info{"branches.branchcode"},
373                 message_transport_type => $transport,
374             }
375           )
376           or warn "no letter of type '$letter_type' found. Please see sample_notices.sql";
377         push @letters, $letter if $letter;
378     }
379
380     if ( @letters ) {
381       if ($nomail) {
382         for my $letter ( @letters ) {
383             local $, = "\f";
384             print $letter->{'content'};
385         }
386       }
387       else {
388         for my $letter ( @letters ) {
389             C4::Letters::EnqueueLetter( { letter                 => $letter,
390                                           borrowernumber         => $borrowernumber,
391                                           from_address           => $from_address,
392                                           message_transport_type => $letter->{message_transport_type} } );
393         }
394       }
395     }
396 }
397
398 # Now, run through all the people that want digests and send them
399 PATRON: while ( my ( $borrowernumber, $digest ) = each %$due_digest ) {
400     @letters = ();
401     my $count = $digest->{count};
402     my $from_address = $digest->{email};
403
404     my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $borrowernumber,
405                                                                                   message_name   => 'item_due' } );
406     next PATRON unless $borrower_preferences; # how could this happen?
407
408     my $letter_type = 'DUEDGST';
409     $sth->execute($borrowernumber,'0');
410     my $titles = "";
411     while ( my $item_info = $sth->fetchrow_hashref()) {
412       my @item_info = map { $_ =~ /^date|date$/ ? format_date($item_info->{$_}) : $item_info->{$_} || '' } @item_content_fields;
413       $titles .= join("\t",@item_info) . "\n";
414     }
415
416     ## Get branch info for borrowers home library.
417     my %branch_info = get_branch_info( $borrowernumber );
418
419     for my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
420         my $letter = parse_letter(
421             {
422                 letter_code    => $letter_type,
423                 borrowernumber => $borrowernumber,
424                 substitute     => {
425                     count           => $count,
426                     'items.content' => $titles,
427                     %branch_info,
428                 },
429                 branchcode             => $branch_info{"branches.branchcode"},
430                 message_transport_type => $transport,
431             }
432           )
433           or warn "no letter of type '$letter_type' found. Please see sample_notices.sql";
434         push @letters, $letter if $letter;
435     }
436
437     if ( @letters ) {
438       if ($nomail) {
439         for my $letter ( @letters ) {
440             local $, = "\f";
441             print $letter->{'content'};
442         }
443       }
444       else {
445         for my $letter ( @letters ) {
446             C4::Letters::EnqueueLetter( { letter                 => $letter,
447                                           borrowernumber         => $borrowernumber,
448                                           from_address           => $from_address,
449                                           message_transport_type => $letter->{message_transport_type} } );
450         }
451       }
452     }
453
454 }
455
456 =head1 METHODS
457
458 =head2 parse_letter
459
460 =cut
461
462 sub parse_letter {
463     my $params = shift;
464     foreach my $required ( qw( letter_code borrowernumber ) ) {
465         return unless exists $params->{$required};
466     }
467
468     my %table_params = ( 'borrowers' => $params->{'borrowernumber'} );
469
470     if ( my $p = $params->{'branchcode'} ) {
471         $table_params{'branches'} = $p;
472     }
473     if ( my $p = $params->{'itemnumber'} ) {
474         $table_params{'issues'} = $p;
475         $table_params{'items'} = $p;
476     }
477     if ( my $p = $params->{'biblionumber'} ) {
478         $table_params{'biblio'} = $p;
479         $table_params{'biblioitems'} = $p;
480     }
481
482     return C4::Letters::GetPreparedLetter (
483         module => 'circulation',
484         letter_code => $params->{'letter_code'},
485         branchcode => $table_params{'branches'},
486         substitute => $params->{'substitute'},
487         tables     => \%table_params,
488         message_transport_type => $params->{message_transport_type},
489     );
490 }
491
492 sub format_date {
493     my $date_string = shift;
494     my $dt=dt_from_string($date_string);
495     return output_pref($dt);
496 }
497
498 =head2 get_branch_info
499
500 =cut
501
502 sub get_branch_info {
503     my ( $borrowernumber ) = @_;
504
505     ## Get branch info for borrowers home library.
506     my $borrower_details = C4::Members::GetMember( borrowernumber => $borrowernumber );
507     my $borrower_branchcode = $borrower_details->{'branchcode'};
508     my $branch = C4::Branch::GetBranchDetail( $borrower_branchcode );
509     my %branch_info;
510     foreach my $key( keys %$branch ) {
511         $branch_info{"branches.$key"} = $branch->{$key};
512     }
513
514     return %branch_info;
515 }
516
517 1;
518
519 __END__