Bug 27049: (QA follow-up) Add short params, replace warn with say
[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 - prepare messages to be sent to patrons for nearly due, or due, items
23
24 =head1 SYNOPSIS
25
26        advance_notices.pl
27          [ -n ][ -m <number of days> ][ --itemscontent <comma separated field list> ][ -c ]
28
29 =head1 DESCRIPTION
30
31 This script prepares pre-due and item due reminders to be sent to
32 patrons. It queues them in the message queue, which is processed by
33 the process_message_queue.pl cronjob. The type and timing of the
34 messages can be configured by the patrons in their "My Alerts" tab in
35 the OPAC.
36
37 =cut
38
39 use strict;
40 use warnings;
41 use Getopt::Long;
42 use Pod::Usage;
43 use Data::Dumper;
44 BEGIN {
45     # find Koha's Perl modules
46     # test carefully before changing this
47     use FindBin;
48     eval { require "$FindBin::Bin/../kohalib.pl" };
49 }
50 use Koha::Script -cron;
51 use C4::Biblio;
52 use C4::Context;
53 use C4::Letters;
54 use C4::Members;
55 use C4::Members::Messaging;
56 use C4::Overdues;
57 use Koha::DateUtils;
58 use C4::Log;
59 use Koha::Items;
60 use Koha::Libraries;
61 use Koha::Patrons;
62
63 =head1 OPTIONS
64
65 =over 8
66
67 =item B<--help>
68
69 Print a brief help message and exits.
70
71 =item B<--man>
72
73 Prints the manual page and exits.
74
75 =item B<-v>
76
77 Verbose. Without this flag set, only fatal errors are reported.
78
79 =item B<-n>
80
81 Do not send any email. Advanced or due notices that would have been sent to
82 the patrons are printed to standard out.
83
84 =item B<-m>
85
86 Defines the maximum number of days in advance to send advance notices.
87
88 =item B<-c>
89
90 Confirm flag: Add this option. The script will only print a usage
91 statement otherwise.
92
93 =item B<--itemscontent>
94
95 comma separated list of fields that get substituted into templates in
96 places of the E<lt>E<lt>items.contentE<gt>E<gt> placeholder. This
97 defaults to date_due,title,author,barcode
98
99 Other possible values come from fields in the biblios, items and
100 issues tables.
101
102 =item B<--digest-per-branch>
103
104 Flag to indicate that generation of message digests should be
105 performed separately for each branch.
106
107 A patron could potentially have loans at several different branches
108 There is no natural branch to set as the sender on the aggregated
109 message in this situation so the default behavior is to use the
110 borrowers home branch.  This could surprise to the borrower when
111 message sender is a library where they have not borrowed anything.
112
113 Enabling this flag ensures that the issuing library is the sender of
114 the digested message.  It has no effect unless the borrower has
115 chosen 'Digests only' on the advance messages.
116
117 =item B<--library>
118
119 select notices for one specific library. Use the value in the
120 branches.branchcode table. This option can be repeated in order
121 to select notices for a group of libraries.
122
123 =item B<--frombranch>
124
125 Set the from address for the notice to one of 'item-homebranch' or 'item-issuebranch'.
126
127 Defaults to 'item-issuebranch'
128
129 =back
130
131 =head2 Configuration
132
133 This script pays attention to the advanced notice configuration
134 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
135 section of Koha is available in the Koha manual.
136
137 =head2 Outgoing emails
138
139 Typically, messages are prepared for each patron with due
140 items, and who have selected (or the library has elected for them) Advance or Due notices.
141
142 These emails are staged in the outgoing message queue, as are messages
143 produced by other features of Koha. This message queue must be
144 processed regularly by the
145 F<misc/cronjobs/process_message_queue.pl> program.
146
147 In the event that the C<-n> flag is passed to this program, no emails
148 are sent. Instead, messages are sent on standard output from this
149 program. They may be redirected to a file if desired.
150
151 =head2 Templates
152
153 Templates can contain variables enclosed in double angle brackets like
154 E<lt>E<lt>thisE<gt>E<gt>. Those variables will be replaced with values
155 specific to the overdue items or relevant patron. Available variables
156 are:
157
158 =over
159
160 =item E<lt>E<lt>items.contentE<gt>E<gt>
161
162 one line for each item, each line containing a tab separated list of
163 date due, title, author, barcode
164
165 =item E<lt>E<lt>borrowers.*E<gt>E<gt>
166
167 any field from the borrowers table
168
169 =item E<lt>E<lt>branches.*E<gt>E<gt>
170
171 any field from the branches table
172
173 =back
174
175 =head1 SEE ALSO
176
177 The F<misc/cronjobs/overdue_notices.pl> program allows you to send
178 messages to patrons when their messages are overdue.
179
180 =cut
181
182 binmode( STDOUT, ':encoding(UTF-8)' );
183
184 # These are defaults for command line options.
185 my $confirm;                                                        # -c: Confirm that the user has read and configured this script.
186 my $nomail;                                                         # -n: No mail. Will not send any emails.
187 my $mindays     = 0;                                                # -m: Maximum number of days in advance to send notices
188 my $maxdays     = 30;                                               # -e: the End of the time period
189 my $verbose     = 0;                                                # -v: verbose
190 my $digest_per_branch = 0;                                          # -digest-per-branch: Prepare and send digests per branch
191 my @branchcodes; # Branch(es) passed as parameter
192 my $frombranch   = 'item-issuebranch';
193 my $itemscontent = join(',',qw( date_due title author barcode ));
194
195 my $help    = 0;
196 my $man     = 0;
197
198 GetOptions(
199             'help|?'         => \$help,
200             'man'            => \$man,
201             'library=s'      => \@branchcodes,
202             'frombranch=s'   => \$frombranch,
203             'c'              => \$confirm,
204             'n'              => \$nomail,
205             'm:i'            => \$maxdays,
206             'v'              => \$verbose,
207             'digest-per-branch' => \$digest_per_branch,
208             'itemscontent=s' => \$itemscontent,
209        )or pod2usage(2);
210 pod2usage(1) if $help;
211 pod2usage( -verbose => 2 ) if $man;
212
213 # Since advance notice options are not visible in the web-interface
214 # unless EnhancedMessagingPreferences is on, let the user know that
215 # this script probably isn't going to do much
216 if ( ! C4::Context->preference('EnhancedMessagingPreferences') ) {
217     warn <<'END_WARN';
218
219 The "EnhancedMessagingPreferences" syspref is off.
220 Therefore, it is unlikely that this script will actually produce any messages to be sent.
221 To change this, edit the "EnhancedMessagingPreferences" syspref.
222
223 END_WARN
224 }
225 unless ($confirm) {
226      pod2usage(1);
227 }
228 cronlogaction();
229
230 my %branches = ();
231 if (@branchcodes) {
232     %branches = map { $_ => 1 } @branchcodes;
233 }
234
235 die "--frombranch takes item-homebranch or item-issuebranch only"
236   unless ( $frombranch eq 'item-issuebranch'
237     || $frombranch eq 'item-homebranch' );
238 my $owning_library = ( $frombranch eq 'item-homebranch' ) ? 1 : 0;
239
240 # The fields that will be substituted into <<items.content>>
241 my @item_content_fields = split(/,/,$itemscontent);
242
243 warn 'getting upcoming due issues' if $verbose;
244 my $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( {
245     days_in_advance => $maxdays,
246     owning_library => $owning_library
247  } );
248 warn 'found ' . scalar( @$upcoming_dues ) . ' issues' if $verbose;
249
250 # hash of borrowernumber to number of items upcoming
251 # for patrons wishing digests only.
252 my $upcoming_digest = {};
253 my $due_digest = {};
254
255 my $dbh = C4::Context->dbh();
256 my $sth = $dbh->prepare(<<'END_SQL');
257 SELECT biblio.*, items.*, issues.*
258   FROM issues,items,biblio
259   WHERE items.itemnumber=issues.itemnumber
260     AND biblio.biblionumber=items.biblionumber
261     AND issues.borrowernumber = ?
262     AND issues.itemnumber = ?
263     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
264 END_SQL
265
266 my $admin_adress = C4::Context->preference('KohaAdminEmailAddress');
267
268 my @letters;
269 UPCOMINGITEM: foreach my $upcoming ( @$upcoming_dues ) {
270     @letters = ();
271     warn 'examining ' . $upcoming->{'itemnumber'} . ' upcoming due items' if $verbose;
272
273     my $from_address = $upcoming->{branchemail} || $admin_adress;
274
275     my $borrower_preferences;
276     if ( 0 == $upcoming->{'days_until_due'} ) {
277         # This item is due today. Send an 'item due' message.
278         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
279                                                                                    message_name   => 'item_due' } );
280         next unless $borrower_preferences;
281         
282         if ( $borrower_preferences->{'wants_digest'} ) {
283             # cache this one to process after we've run through all of the items.
284             if ($digest_per_branch) {
285                 $due_digest->{ $upcoming->{branchcode} }->{ $upcoming->{borrowernumber} }->{email} = $from_address;
286                 $due_digest->{ $upcoming->{branchcode} }->{ $upcoming->{borrowernumber} }->{count}++;
287             } else {
288                 $due_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
289                 $due_digest->{ $upcoming->{borrowernumber} }->{count}++;
290             }
291         } else {
292             my $branchcode;
293             if($owning_library) {
294                 $branchcode = $upcoming->{'homebranch'};
295             } else {
296                 $branchcode = $upcoming->{'branchcode'};
297             }
298             # Skip this DUE if we specify list of libraries and this one is not part of it
299             next if (@branchcodes && !$branches{$branchcode});
300
301             my $item = Koha::Items->find( $upcoming->{itemnumber} );
302             my $letter_type = 'DUE';
303             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},'0');
304             my $titles = "";
305             while ( my $item_info = $sth->fetchrow_hashref()) {
306                 $titles .= C4::Letters::get_item_content( { item => $item_info, item_content_fields => \@item_content_fields } );
307             }
308
309             ## Get branch info for borrowers home library.
310             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
311                 my $letter = parse_letter( { letter_code    => $letter_type,
312                                       borrowernumber => $upcoming->{'borrowernumber'},
313                                       branchcode     => $branchcode,
314                                       biblionumber   => $item->biblionumber,
315                                       itemnumber     => $upcoming->{'itemnumber'},
316                                       substitute     => { 'items.content' => $titles },
317                                       message_transport_type => $transport,
318                                     } )
319                     or warn "no letter of type '$letter_type' found for borrowernumber ".$upcoming->{'borrowernumber'}.". Please see sample_notices.sql";
320                 push @letters, $letter if $letter;
321             }
322         }
323     } else {
324         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
325                                                                                    message_name   => 'advance_notice' } );
326         next UPCOMINGITEM unless $borrower_preferences && exists $borrower_preferences->{'days_in_advance'};
327         next UPCOMINGITEM unless $borrower_preferences->{'days_in_advance'} == $upcoming->{'days_until_due'};
328
329         if ( $borrower_preferences->{'wants_digest'} ) {
330             # cache this one to process after we've run through all of the items.
331             if ($digest_per_branch) {
332                 $upcoming_digest->{ $upcoming->{branchcode} }->{ $upcoming->{borrowernumber} }->{email} = $from_address;
333                 $upcoming_digest->{ $upcoming->{branchcode} }->{ $upcoming->{borrowernumber} }->{count}++;
334             } else {
335                 $upcoming_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
336                 $upcoming_digest->{ $upcoming->{borrowernumber} }->{count}++;
337             }
338         } else {
339             my $branchcode;
340             if($owning_library) {
341             $branchcode = $upcoming->{'homebranch'};
342             } else {
343             $branchcode = $upcoming->{'branchcode'};
344             }
345             # Skip this PREDUE if we specify list of libraries and this one is not part of it
346             next if (@branchcodes && !$branches{$branchcode});
347
348             my $item = Koha::Items->find( $upcoming->{itemnumber} );
349             my $letter_type = 'PREDUE';
350             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},$borrower_preferences->{'days_in_advance'});
351             my $titles = "";
352             while ( my $item_info = $sth->fetchrow_hashref()) {
353                 $titles .= C4::Letters::get_item_content( { item => $item_info, item_content_fields => \@item_content_fields } );
354             }
355
356             ## Get branch info for borrowers home library.
357             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
358                 my $letter = parse_letter( { letter_code    => $letter_type,
359                                       borrowernumber => $upcoming->{'borrowernumber'},
360                                       branchcode     => $branchcode,
361                                       biblionumber   => $item->biblionumber,
362                                       itemnumber     => $upcoming->{'itemnumber'},
363                                       substitute     => { 'items.content' => $titles },
364                                       message_transport_type => $transport,
365                                     } )
366                     or warn "no letter of type '$letter_type' found for borrowernumber ".$upcoming->{'borrowernumber'}.". Please see sample_notices.sql";
367                 push @letters, $letter if $letter;
368             }
369         }
370     }
371
372     # If we have prepared a letter, send it.
373     if ( @letters ) {
374       if ($nomail) {
375         for my $letter ( @letters ) {
376             local $, = "\f";
377             print $letter->{'content'}."\n";
378         }
379       }
380       else {
381         for my $letter ( @letters ) {
382             C4::Letters::EnqueueLetter( { letter                 => $letter,
383                                           borrowernumber         => $upcoming->{'borrowernumber'},
384                                           from_address           => $from_address,
385                                           message_transport_type => $letter->{message_transport_type} } );
386         }
387       }
388     }
389 }
390
391
392
393 # Now, run through all the people that want digests and send them
394
395 my $sth_digest = $dbh->prepare(<<'END_SQL');
396 SELECT biblio.*, items.*, issues.*
397   FROM issues,items,biblio
398   WHERE items.itemnumber=issues.itemnumber
399     AND biblio.biblionumber=items.biblionumber
400     AND issues.borrowernumber = ?
401     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
402 END_SQL
403
404 if ($digest_per_branch) {
405     while (my ($branchcode, $digests) = each %$upcoming_digest) {
406         send_digests({
407             sth => $sth_digest,
408             digests => $digests,
409             letter_code => 'PREDUEDGST',
410             message_name => 'advance_notice',
411             branchcode => $branchcode,
412             get_item_info => sub {
413                 my $params = shift;
414                 $params->{sth}->execute($params->{borrowernumber},
415                                         $params->{borrower_preferences}->{'days_in_advance'});
416                 return sub {
417                     $params->{sth}->fetchrow_hashref;
418                 };
419             }
420         });
421     }
422
423     while (my ($branchcode, $digests) = each %$due_digest) {
424         send_digests({
425             sth => $sth_digest,
426             digests => $due_digest,
427             letter_code => 'DUEDGST',
428             branchcode => $branchcode,
429             message_name => 'item_due',
430             get_item_info => sub {
431                 my $params = shift;
432                 $params->{sth}->execute($params->{borrowernumber}, 0);
433                 return sub {
434                     $params->{sth}->fetchrow_hashref;
435                 };
436             }
437         });
438     }
439 } else {
440     send_digests({
441         sth => $sth_digest,
442         digests => $upcoming_digest,
443         letter_code => 'PREDUEDGST',
444         message_name => 'advance_notice',
445         get_item_info => sub {
446             my $params = shift;
447             $params->{sth}->execute($params->{borrowernumber},
448                                     $params->{borrower_preferences}->{'days_in_advance'});
449             return sub {
450                 $params->{sth}->fetchrow_hashref;
451             };
452         }
453     });
454
455     send_digests({
456         sth => $sth_digest,
457         digests => $due_digest,
458         letter_code => 'DUEDGST',
459         message_name => 'item_due',
460         get_item_info => sub {
461             my $params = shift;
462             $params->{sth}->execute($params->{borrowernumber}, 0);
463             return sub {
464                 $params->{sth}->fetchrow_hashref;
465             };
466         }
467     });
468 }
469
470 =head1 METHODS
471
472 =head2 parse_letter
473
474 =cut
475
476 sub parse_letter {
477     my $params = shift;
478
479     foreach my $required ( qw( letter_code borrowernumber ) ) {
480         return unless exists $params->{$required};
481     }
482     my $patron = Koha::Patrons->find( $params->{borrowernumber} );
483
484     my %table_params = ( 'borrowers' => $params->{'borrowernumber'} );
485
486     if ( my $p = $params->{'branchcode'} ) {
487         $table_params{'branches'} = $p;
488     }
489     if ( my $p = $params->{'itemnumber'} ) {
490         $table_params{'issues'} = $p;
491         $table_params{'items'} = $p;
492     }
493     if ( my $p = $params->{'biblionumber'} ) {
494         $table_params{'biblio'} = $p;
495         $table_params{'biblioitems'} = $p;
496     }
497
498     return C4::Letters::GetPreparedLetter (
499         module => 'circulation',
500         letter_code => $params->{'letter_code'},
501         branchcode => $table_params{'branches'},
502         lang => $patron->lang,
503         substitute => $params->{'substitute'},
504         tables     => \%table_params,
505         message_transport_type => $params->{message_transport_type},
506     );
507 }
508
509 =head2 get_branch_info
510
511 =cut
512
513 sub get_branch_info {
514     my ( $borrowernumber ) = @_;
515
516     ## Get branch info for borrowers home library.
517     my $patron = Koha::Patrons->find( $borrowernumber );
518     my $branch = $patron->library->unblessed;
519     my %branch_info;
520     foreach my $key( keys %$branch ) {
521         $branch_info{"branches.$key"} = $branch->{$key};
522     }
523
524     return %branch_info;
525 }
526
527 =head2 send_digests
528
529     send_digests({
530         digests => ...,
531         sth => ...,
532         letter_code => ...,
533         get_item_info => ...,
534     })
535
536 Enqueue digested letters (or print them if -n was passed at command line).
537
538 Parameters:
539
540 =over 4
541
542 =item C<$digests>
543
544 Reference to the array of digested messages.
545
546 =item C<$sth>
547
548 Prepared statement handle for fetching overdue issues.
549
550 =item C<$letter_code>
551
552 String that denote the letter code.
553
554 =item C<$get_item_info>
555
556 Subroutine for executing prepared statement.  Takes parameters $sth,
557 $borrowernumber and $borrower_parameters and return a generator
558 function that produce the matching rows.
559
560 =back
561
562 =cut
563
564 sub send_digests {
565     my $params = shift;
566
567     PATRON: while ( my ( $borrowernumber, $digest ) = each %{$params->{digests}} ) {
568         @letters = ();
569         my $count = $digest->{count};
570         my $from_address = $digest->{email};
571
572         my %branch_info;
573         my $branchcode;
574
575         if (defined($params->{branchcode})) {
576             %branch_info = ();
577             $branchcode = $params->{branchcode};
578         } else {
579             ## Get branch info for borrowers home library.
580             %branch_info = get_branch_info( $borrowernumber );
581             $branchcode = $branch_info{'branches.branchcode'};
582         }
583
584         my $borrower_preferences =
585             C4::Members::Messaging::GetMessagingPreferences(
586                 {
587                     borrowernumber => $borrowernumber,
588                     message_name   => $params->{message_name}
589                 }
590             );
591
592         next PATRON unless $borrower_preferences; # how could this happen?
593
594         my $next_item_info = $params->{get_item_info}->({
595             sth => $params->{sth},
596             borrowernumber => $borrowernumber,
597             borrower_preferences => $borrower_preferences
598         });
599         my $titles = "";
600         while ( my $item_info = $next_item_info->()) {
601             $titles .= C4::Letters::get_item_content( { item => $item_info, item_content_fields => \@item_content_fields } );
602         }
603
604         foreach my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
605             my $letter = parse_letter(
606                 {
607                     letter_code    => $params->{letter_code},
608                     borrowernumber => $borrowernumber,
609                     substitute     => {
610                         count           => $count,
611                         'items.content' => $titles,
612                         %branch_info
613                     },
614                     branchcode     => $branchcode,
615                     message_transport_type => $transport
616                 }
617             );
618             unless ( $letter ){
619                 warn "no letter of type '$params->{letter_type}' found for borrowernumber $borrowernumber. Please see sample_notices.sql";
620                 next;
621             }
622             push @letters, $letter if $letter;
623         }
624
625         if ( @letters ) {
626             if ($nomail) {
627                 for my $letter ( @letters ) {
628                     local $, = "\f";
629                     print $letter->{'content'};
630                 }
631             }
632             else {
633                 for my $letter ( @letters ) {
634                     C4::Letters::EnqueueLetter( { letter                 => $letter,
635                                                   borrowernumber         => $borrowernumber,
636                                                   from_address           => $from_address,
637                                                   message_transport_type => $letter->{message_transport_type} } );
638                 }
639             }
640         }
641     }
642 }
643
644
645 1;
646
647 __END__