Bug 20478: Refactor to remove code duplication.
[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 =back
113
114 =head1 DESCRIPTION
115
116 This script is designed to alert patrons when items are due, or coming due
117
118 =head2 Configuration
119
120 This script pays attention to the advanced notice configuration
121 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
122 section of Koha is available in the Koha manual.
123
124 =head2 Outgoing emails
125
126 Typically, messages are prepared for each patron with due
127 items, and who have selected (or the library has elected for them) Advance or Due notices.
128
129 These emails are staged in the outgoing message queue, as are messages
130 produced by other features of Koha. This message queue must be
131 processed regularly by the
132 F<misc/cronjobs/process_message_queue.pl> program.
133
134 In the event that the C<-n> flag is passed to this program, no emails
135 are sent. Instead, messages are sent on standard output from this
136 program. They may be redirected to a file if desired.
137
138 =head2 Templates
139
140 Templates can contain variables enclosed in double angle brackets like
141 E<lt>E<lt>thisE<gt>E<gt>. Those variables will be replaced with values
142 specific to the overdue items or relevant patron. Available variables
143 are:
144
145 =over
146
147 =item E<lt>E<lt>items.contentE<gt>E<gt>
148
149 one line for each item, each line containing a tab separated list of
150 date due, title, author, barcode
151
152 =item E<lt>E<lt>borrowers.*E<gt>E<gt>
153
154 any field from the borrowers table
155
156 =item E<lt>E<lt>branches.*E<gt>E<gt>
157
158 any field from the branches table
159
160 =back
161
162 =head1 SEE ALSO
163
164 The F<misc/cronjobs/overdue_notices.pl> program allows you to send
165 messages to patrons when their messages are overdue.
166
167 =cut
168
169 binmode( STDOUT, ':encoding(UTF-8)' );
170
171 # These are defaults for command line options.
172 my $confirm;                                                        # -c: Confirm that the user has read and configured this script.
173 my $nomail;                                                         # -n: No mail. Will not send any emails.
174 my $mindays     = 0;                                                # -m: Maximum number of days in advance to send notices
175 my $maxdays     = 30;                                               # -e: the End of the time period
176 my $verbose     = 0;                                                # -v: verbose
177 my $itemscontent = join(',',qw( date_due title author barcode ));
178
179 my $help    = 0;
180 my $man     = 0;
181
182 GetOptions(
183             'help|?'         => \$help,
184             'man'            => \$man,
185             'c'              => \$confirm,
186             'n'              => \$nomail,
187             'm:i'            => \$maxdays,
188             'v'              => \$verbose,
189             'itemscontent=s' => \$itemscontent,
190        )or pod2usage(2);
191 pod2usage(1) if $help;
192 pod2usage( -verbose => 2 ) if $man;
193
194 # Since advance notice options are not visible in the web-interface
195 # unless EnhancedMessagingPreferences is on, let the user know that
196 # this script probably isn't going to do much
197 if ( ! C4::Context->preference('EnhancedMessagingPreferences') ) {
198     warn <<'END_WARN';
199
200 The "EnhancedMessagingPreferences" syspref is off.
201 Therefore, it is unlikely that this script will actually produce any messages to be sent.
202 To change this, edit the "EnhancedMessagingPreferences" syspref.
203
204 END_WARN
205 }
206 unless ($confirm) {
207      pod2usage(1);
208 }
209
210 cronlogaction();
211
212 # The fields that will be substituted into <<items.content>>
213 my @item_content_fields = split(/,/,$itemscontent);
214
215 warn 'getting upcoming due issues' if $verbose;
216 my $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $maxdays } );
217 warn 'found ' . scalar( @$upcoming_dues ) . ' issues' if $verbose;
218
219 # hash of borrowernumber to number of items upcoming
220 # for patrons wishing digests only.
221 my $upcoming_digest;
222 my $due_digest;
223
224 my $dbh = C4::Context->dbh();
225 my $sth = $dbh->prepare(<<'END_SQL');
226 SELECT biblio.*, items.*, issues.*
227   FROM issues,items,biblio
228   WHERE items.itemnumber=issues.itemnumber
229     AND biblio.biblionumber=items.biblionumber
230     AND issues.borrowernumber = ?
231     AND issues.itemnumber = ?
232     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
233 END_SQL
234
235 my $admin_adress = C4::Context->preference('KohaAdminEmailAddress');
236
237 my @letters;
238 UPCOMINGITEM: foreach my $upcoming ( @$upcoming_dues ) {
239     @letters = ();
240     warn 'examining ' . $upcoming->{'itemnumber'} . ' upcoming due items' if $verbose;
241
242     my $from_address = $upcoming->{branchemail} || $admin_adress;
243
244     my $borrower_preferences;
245     if ( 0 == $upcoming->{'days_until_due'} ) {
246         # This item is due today. Send an 'item due' message.
247         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
248                                                                                    message_name   => 'item_due' } );
249         next unless $borrower_preferences;
250         
251         if ( $borrower_preferences->{'wants_digest'} ) {
252             # cache this one to process after we've run through all of the items.
253             $due_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
254             $due_digest->{ $upcoming->{borrowernumber} }->{count}++;
255         } else {
256             my $item = Koha::Items->find( $upcoming->{itemnumber} );
257             my $letter_type = 'DUE';
258             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},'0');
259             my $titles = "";
260             while ( my $item_info = $sth->fetchrow_hashref()) {
261                 $titles .= C4::Letters::get_item_content( { item => $item_info, item_content_fields => \@item_content_fields } );
262             }
263
264             ## Get branch info for borrowers home library.
265             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
266                 my $letter = parse_letter( { letter_code    => $letter_type,
267                                       borrowernumber => $upcoming->{'borrowernumber'},
268                                       branchcode     => $upcoming->{'branchcode'},
269                                       biblionumber   => $item->biblionumber,
270                                       itemnumber     => $upcoming->{'itemnumber'},
271                                       substitute     => { 'items.content' => $titles },
272                                       message_transport_type => $transport,
273                                     } )
274                     or warn "no letter of type '$letter_type' found for borrowernumber ".$upcoming->{'borrowernumber'}.". Please see sample_notices.sql";
275                 push @letters, $letter if $letter;
276             }
277         }
278     } else {
279         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $upcoming->{'borrowernumber'},
280                                                                                    message_name   => 'advance_notice' } );
281         next UPCOMINGITEM unless $borrower_preferences && exists $borrower_preferences->{'days_in_advance'};
282         next UPCOMINGITEM unless $borrower_preferences->{'days_in_advance'} == $upcoming->{'days_until_due'};
283
284         if ( $borrower_preferences->{'wants_digest'} ) {
285             # cache this one to process after we've run through all of the items.
286             $upcoming_digest->{ $upcoming->{borrowernumber} }->{email} = $from_address;
287             $upcoming_digest->{ $upcoming->{borrowernumber} }->{count}++;
288         } else {
289             my $item = Koha::Items->find( $upcoming->{itemnumber} );
290             my $letter_type = 'PREDUE';
291             $sth->execute($upcoming->{'borrowernumber'},$upcoming->{'itemnumber'},$borrower_preferences->{'days_in_advance'});
292             my $titles = "";
293             while ( my $item_info = $sth->fetchrow_hashref()) {
294                 $titles .= C4::Letters::get_item_content( { item => $item_info, item_content_fields => \@item_content_fields } );
295             }
296
297             ## Get branch info for borrowers home library.
298             foreach my $transport ( keys %{$borrower_preferences->{'transports'}} ) {
299                 my $letter = parse_letter( { letter_code    => $letter_type,
300                                       borrowernumber => $upcoming->{'borrowernumber'},
301                                       branchcode     => $upcoming->{'branchcode'},
302                                       biblionumber   => $item->biblionumber,
303                                       itemnumber     => $upcoming->{'itemnumber'},
304                                       substitute     => { 'items.content' => $titles },
305                                       message_transport_type => $transport,
306                                     } )
307                     or warn "no letter of type '$letter_type' found for borrowernumber ".$upcoming->{'borrowernumber'}.". Please see sample_notices.sql";
308                 push @letters, $letter if $letter;
309             }
310         }
311     }
312
313     # If we have prepared a letter, send it.
314     if ( @letters ) {
315       if ($nomail) {
316         for my $letter ( @letters ) {
317             local $, = "\f";
318             print $letter->{'content'};
319         }
320       }
321       else {
322         for my $letter ( @letters ) {
323             C4::Letters::EnqueueLetter( { letter                 => $letter,
324                                           borrowernumber         => $upcoming->{'borrowernumber'},
325                                           from_address           => $from_address,
326                                           message_transport_type => $letter->{message_transport_type} } );
327         }
328       }
329     }
330 }
331
332
333
334 # Now, run through all the people that want digests and send them
335
336 my $sth_digest = $dbh->prepare(<<'END_SQL');
337 SELECT biblio.*, items.*, issues.*
338   FROM issues,items,biblio
339   WHERE items.itemnumber=issues.itemnumber
340     AND biblio.biblionumber=items.biblionumber
341     AND issues.borrowernumber = ?
342     AND (TO_DAYS(date_due)-TO_DAYS(NOW()) = ?)
343 END_SQL
344
345 send_digests({
346     sth => $sth_digest,
347     digests => $upcoming_digest,
348     letter_code => 'PREDUEDGST',
349     get_item_info => sub {
350         my $params = shift;
351         $params->{sth}->execute($params->{borrowernumber},
352                       $params->{borrower_preferences}->{'days_in_advance'});
353         return sub {
354             $params->{sth}->fetchrow_hashref;
355         };
356     }
357 });
358
359 send_digests({
360     sth => $sth_digest,
361     digest => $due_digest,
362     letter_code => 'DUEGST',
363     get_item_info => sub {
364         my $params = shift;
365         $params->{sth}->execute($params->{borrowernumber}, 0);
366         return sub {
367             $params->{sth}->fetchrow_hashref;
368         };
369     }
370 });
371
372 =head1 METHODS
373
374 =head2 parse_letter
375
376 =cut
377
378 sub parse_letter {
379     my $params = shift;
380
381     foreach my $required ( qw( letter_code borrowernumber ) ) {
382         return unless exists $params->{$required};
383     }
384     my $patron = Koha::Patrons->find( $params->{borrowernumber} );
385
386     my %table_params = ( 'borrowers' => $params->{'borrowernumber'} );
387
388     if ( my $p = $params->{'branchcode'} ) {
389         $table_params{'branches'} = $p;
390     }
391     if ( my $p = $params->{'itemnumber'} ) {
392         $table_params{'issues'} = $p;
393         $table_params{'items'} = $p;
394     }
395     if ( my $p = $params->{'biblionumber'} ) {
396         $table_params{'biblio'} = $p;
397         $table_params{'biblioitems'} = $p;
398     }
399
400     return C4::Letters::GetPreparedLetter (
401         module => 'circulation',
402         letter_code => $params->{'letter_code'},
403         branchcode => $table_params{'branches'},
404         lang => $patron->lang,
405         substitute => $params->{'substitute'},
406         tables     => \%table_params,
407         message_transport_type => $params->{message_transport_type},
408     );
409 }
410
411 =head2 get_branch_info
412
413 =cut
414
415 sub get_branch_info {
416     my ( $borrowernumber ) = @_;
417
418     ## Get branch info for borrowers home library.
419     my $patron = Koha::Patrons->find( $borrowernumber );
420     my $branch = $patron->library->unblessed;
421     my %branch_info;
422     foreach my $key( keys %$branch ) {
423         $branch_info{"branches.$key"} = $branch->{$key};
424     }
425
426     return %branch_info;
427 }
428
429 =head2 send_digests
430
431     send_digests({
432         digests => ...,
433         sth => ...,
434         letter_code => ...,
435         get_item_info => ...,
436     })
437
438 Enqueue digested letters (or print them if -n was passed at command line).
439
440 Parameters:
441
442 =over 4
443
444 =item C<$digests>
445
446 Reference to the array of digested messages.
447
448 =item C<$sth>
449
450 Prepared statement handle for fetching overdue issues.
451
452 =item C<$letter_code>
453
454 String that denote the letter code.
455
456 =item C<$get_item_info>
457
458 Subroutine for executing prepared statement.  Takes parameters $sth,
459 $borrowernumber and $borrower_parameters and return a generator
460 function that produce the matching rows.
461
462 =back
463
464 =cut
465
466 sub send_digests {
467     my $params = shift;
468
469     PATRON: while ( my ( $borrowernumber, $digest ) = each %{$params->{digests}} ) {
470         @letters = ();
471         my $count = $digest->{count};
472         my $from_address = $digest->{email};
473
474         my $borrower_preferences =
475             C4::Members::Messaging::GetMessagingPreferences(
476                 {
477                     borrowernumber => $borrowernumber,
478                     message_name   => 'advance_notice'
479                 }
480             );
481
482         next PATRON unless $borrower_preferences; # how could this happen?
483
484         my $next_item_info = $params->{get_item_info}->({
485             sth => $params->{sth},
486             borrowernumber => $borrowernumber,
487             borrower_preferences => $borrower_preferences
488         });
489         my $titles = "";
490         while ( my $item_info = $next_item_info->()) {
491             $titles .= C4::Letters::get_item_content( { item => $item_info, item_content_fields => \@item_content_fields } );
492         }
493
494         ## Get branch info for borrowers home library.
495         my %branch_info = get_branch_info( $borrowernumber );
496
497         foreach my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
498             my $letter = parse_letter(
499                 {
500                     letter_code    => $params->{letter_code},
501                     borrowernumber => $borrowernumber,
502                     substitute     => {
503                         count           => $count,
504                         'items.content' => $titles,
505                         %branch_info,
506                     },
507                     branchcode             => $branch_info{"branches.branchcode"},
508                     message_transport_type => $transport,
509                 }
510                 )
511                 or warn "no letter of type '$params->{letter_type}' found for borrowernumber $borrowernumber. Please see sample_notices.sql";
512             push @letters, $letter if $letter;
513         }
514
515         if ( @letters ) {
516             if ($nomail) {
517                 for my $letter ( @letters ) {
518                     local $, = "\f";
519                     print $letter->{'content'};
520                 }
521             }
522             else {
523                 for my $letter ( @letters ) {
524                     C4::Letters::EnqueueLetter( { letter                 => $letter,
525                                                   borrowernumber         => $borrowernumber,
526                                                   from_address           => $from_address,
527                                                   message_transport_type => $letter->{message_transport_type} } );
528                 }
529             }
530         }
531     }
532 }
533
534
535 1;
536
537 __END__