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