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