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