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