Bug 34924: Add 'auto_renew_final' and 'auto_unseen_final' return to CanBookBeRenewed
[koha.git] / misc / cronjobs / automatic_renewals.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Copyright (C) 2014 Hochschule für Gesundheit (hsg), Germany
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 automatic_renewals.pl - cron script to renew loans
23
24 =head1 SYNOPSIS
25
26 ./automatic_renewals.pl [-c|--confirm] [-s|--send-notices] [-d|--digest] [-b|--digest-per-branch] [-v|--verbose]
27
28 or, in crontab:
29 # Once every day for digest messages
30 0 3 * * * automatic_renewals.pl -c -d
31 # Three times a day for non digest messages
32 0 0,8,16 * * * automatic_renewals.pl -c
33
34 =head1 DESCRIPTION
35
36 This script searches for issues scheduled for automatic renewal
37 (issues.auto_renew). If there are still renews left (Renewals allowed)
38 and the renewal isn't premature (No Renewal before) the issue is renewed.
39
40 =head1 OPTIONS
41
42 =over
43
44 =item B<-s|--send-notices>
45
46 DEPRECATED: The system preference AutoRenewalNotices should be used to determine
47 whether notices are sent or not
48 Send AUTO_RENEWALS notices to patrons if the auto renewal has been done.
49
50 =item B<-v|--verbose>
51
52 Print report to standard out.
53
54 =item B<-c|--confirm>
55
56 Without this parameter no changes will be made
57
58 =item B<-b|--digest-per-branch>
59
60 Flag to indicate that generation of message digests should be
61 performed separately for each branch.
62
63 A patron could potentially have loans at several different branches
64 There is no natural branch to set as the sender on the aggregated
65 message in this situation so the default behavior is to use the
66 borrowers home branch.  This could surprise to the borrower when
67 message sender is a library where they have not borrowed anything.
68
69 Enabling this flag ensures that the issuing library is the sender of
70 the digested message.  It has no effect unless the borrower has
71 chosen 'Digests only' on the advance messages.
72
73 =back
74
75 =cut
76
77 use Modern::Perl;
78 use Pod::Usage qw( pod2usage );
79 use Getopt::Long qw( GetOptions );
80
81 use Koha::Script -cron;
82 use C4::Circulation qw( CanBookBeRenewed AddRenewal );
83 use C4::Context;
84 use C4::Log qw( cronlogaction );
85 use C4::Letters;
86 use Koha::Checkouts;
87 use Koha::Libraries;
88 use Koha::Patrons;
89
90 my $command_line_options = join(" ",@ARGV);
91
92 my ( $help, $send_notices, $verbose, $confirm, $digest_per_branch );
93 GetOptions(
94     'h|help' => \$help,
95     's|send-notices' => \$send_notices,
96     'v|verbose'    => \$verbose,
97     'c|confirm'     => \$confirm,
98     'b|digest-per-branch' => \$digest_per_branch,
99 ) || pod2usage(1);
100
101 pod2usage(0) if $help;
102
103 my $send_notices_pref = C4::Context->preference('AutoRenewalNotices');
104 if ( $send_notices_pref eq 'cron' ) {
105     warn <<'END_WARN';
106
107 The "AutoRenewalNotices" syspref is set to 'Follow the cron switch'.
108 The send_notices switch for this script is deprecated, you should either set the preference
109 to 'Never send emails' or 'Follow patron messaging preferences'
110
111 END_WARN
112 } else {
113     # If not following cron then:
114     # - we should not send if set to never
115     # - we will send any notice generated according to preferences if following those
116     $send_notices = $send_notices_pref eq 'never' ? 0 : 1;
117 }
118
119 # Since advance notice options are not visible in the web-interface
120 # unless EnhancedMessagingPreferences is on, let the user know that
121 # this script probably isn't going to do much
122 if ( ! C4::Context->preference('EnhancedMessagingPreferences') ) {
123     warn <<'END_WARN';
124
125 The "EnhancedMessagingPreferences" syspref is off.
126 Therefore, it is unlikely that this script will actually produce any messages to be sent.
127 To change this, edit the "EnhancedMessagingPreferences" syspref.
128
129 END_WARN
130 }
131
132 cronlogaction({ info => $command_line_options });
133
134 $verbose = 1 unless $verbose or $confirm;
135 print "Test run only\n" unless $confirm;
136
137 print "getting auto renewals\n" if $verbose;
138 my $auto_renews = Koha::Checkouts->search(
139     {
140         auto_renew                   => 1,
141         'patron.autorenew_checkouts' => 1,
142     },
143     {
144         join => ['patron','item']
145     }
146 );
147 print "found " . $auto_renews->count . " auto renewals\n" if $verbose;
148
149 my $renew_digest = {};
150 my %report;
151 my @item_renewal_ids;
152 while ( my $auto_renew = $auto_renews->next ) {
153     print "examining item '" . $auto_renew->itemnumber . "' to auto renew\n" if $verbose;
154
155     my ( $borrower_preferences, $wants_messages, $wants_digest ) = ( undef, 0, 0 );
156     if ( $send_notices_pref eq 'preferences' ) {
157         $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences(
158             {
159                 borrowernumber => $auto_renew->borrowernumber,
160                 message_name   => 'auto_renewals'
161             }
162         );
163         $wants_messages = 1
164             if $borrower_preferences
165             && $borrower_preferences->{transports};
166         $wants_digest = 1
167             if $wants_messages
168             && $borrower_preferences->{wants_digest};
169     } else {    # Preference is never or cron
170         $wants_messages = $send_notices;
171         $wants_digest   = 0;
172     }
173
174     my ( $success, $error, $updated ) = $auto_renew->attempt_auto_renew( { confirm => $confirm } );
175     if ($success) {
176         if ($verbose) {
177             say sprintf "Issue id: %s for borrower: %s and item: %s %s be renewed.",
178                 $auto_renew->issue_id, $auto_renew->borrowernumber, $auto_renew->itemnumber,
179                 $confirm ? 'will' : 'would';
180         }
181         if ($confirm) {
182             push @item_renewal_ids, $auto_renew->itemnumber;
183         }
184         push @{ $report{ $auto_renew->borrowernumber } }, $auto_renew
185             if ($wants_messages) && !$wants_digest;
186     } elsif (
187
188         # FIXME Do we need to list every status? Why not simply else?
189            $error eq 'too_many'
190         || $error eq 'on_reserve'
191         || $error eq 'restriction'
192         || $error eq 'overdue'
193         || $error eq 'too_unseen'
194         || $error eq 'auto_account_expired'
195         || $error eq 'auto_too_late'
196         || $error eq 'auto_too_much_oweing'
197         || $error eq 'auto_too_soon'
198         || $error eq 'item_denied_renewal'
199         || $error eq 'item_issued_to_other_patron'
200         )
201     {
202         if ($verbose) {
203             say sprintf "Issue id: %s for borrower: %s and item: %s %s not be renewed. (%s)",
204                 $auto_renew->issue_id, $auto_renew->borrowernumber, $auto_renew->itemnumber,
205                 $confirm ? 'will' : 'would', $error;
206         }
207         if ($updated) {
208             push @{ $report{ $auto_renew->borrowernumber } }, $auto_renew
209                 if $error ne 'auto_too_soon' && ( $wants_messages && !$wants_digest );  # Do not notify if it's too soon
210         }
211     }
212
213     if ( $wants_digest ) {
214         # cache this one to process after we've run through all of the items.
215         if ($digest_per_branch) {
216             $renew_digest->{ $auto_renew->branchcode }->{ $auto_renew->borrowernumber }->{success}++ if $error eq 'auto_renew';
217             $renew_digest->{ $auto_renew->branchcode }->{ $auto_renew->borrowernumber }->{error}++ unless $error eq 'auto_renew' || $error eq 'auto_too_soon';
218             $renew_digest->{ $auto_renew->branchcode }->{ $auto_renew->borrowernumber }->{results}->{$error}++ ;
219             push @{$renew_digest->{ $auto_renew->branchcode }->{ $auto_renew->borrowernumber }->{issues}}, $auto_renew->itemnumber;
220             $renew_digest->{ $auto_renew->branchcode }->{ $auto_renew->borrowernumber }->{updated} = 1 if $updated && $error ne 'auto_too_soon';
221         } else {
222             $renew_digest->{ $auto_renew->borrowernumber }->{success} ++ if $error eq 'auto_renew';
223             $renew_digest->{ $auto_renew->borrowernumber }->{error}++ unless $error eq 'auto_renew' || $error eq 'auto_too_soon';
224             $renew_digest->{ $auto_renew->borrowernumber }->{results}->{$error}++ ;
225             $renew_digest->{ $auto_renew->borrowernumber }->{updated} = 1 if $updated && $error ne 'auto_too_soon';
226             push @{$renew_digest->{ $auto_renew->borrowernumber }->{issues}}, $auto_renew->itemnumber;
227         }
228     }
229
230 }
231
232 if( @item_renewal_ids ){
233     my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
234     $indexer->index_records( \@item_renewal_ids, "specialUpdate", "biblioserver" );
235 }
236
237 if ( $send_notices && $confirm ) {
238     for my $borrowernumber ( keys %report ) {
239         my $patron = Koha::Patrons->find($borrowernumber);
240         my $borrower_preferences =
241             C4::Members::Messaging::GetMessagingPreferences(
242                 {
243                     borrowernumber => $borrowernumber,
244                     message_name   => 'auto_renewals'
245                 }
246             );
247         for my $issue ( @{ $report{$borrowernumber} } ) {
248             my $item = $issue->item;
249             # Force sending of email and only email if pref is set to "cron"
250             my @transports = $send_notices_pref eq 'preferences' ? keys %{ $borrower_preferences->{'transports'} } : 'email';
251             foreach my $transport ( @transports ) {
252                 my $letter = C4::Letters::GetPreparedLetter (
253                     module      => 'circulation',
254                     letter_code => 'AUTO_RENEWALS',
255                     tables      => {
256                         borrowers => $patron->borrowernumber,
257                         issues    => $issue->itemnumber,
258                         items     => $issue->itemnumber,
259                         biblio    => $item->biblionumber,
260                     },
261                     lang => $patron->lang,
262                     message_transport_type => $transport,
263                 );
264
265                 if ($letter) {
266                     my $library = $patron->library;
267                     my $admin_email_address = $library->from_email_address;
268
269                     C4::Letters::EnqueueLetter(
270                         {
271                             letter                 => $letter,
272                             borrowernumber         => $borrowernumber,
273                             from_address           => $admin_email_address,
274                             message_transport_type => $transport
275                         }
276                     );
277                 }
278             }
279         }
280     }
281
282     if ($digest_per_branch) {
283         while (my ($branchcode, $digests) = each %$renew_digest) {
284             send_digests({
285                 digests => $digests,
286                 branchcode => $branchcode,
287                 letter_code => 'AUTO_RENEWALS_DGST',
288             });
289         }
290     } else {
291         send_digests({
292             digests => $renew_digest,
293             letter_code => 'AUTO_RENEWALS_DGST',
294         });
295     }
296 }
297
298 cronlogaction({ action => 'End', info => "COMPLETED" });
299
300 =head1 METHODS
301
302 =head2 send_digests
303
304     send_digests({
305         digests => ...,
306         letter_code => ...,
307     })
308
309 Enqueue digested letters.
310
311 Parameters:
312
313 =over 4
314
315 =item C<$digests>
316
317 Reference to the array of digested messages.
318
319 =item C<$letter_code>
320
321 String that denote the letter code.
322
323 =back
324
325 =cut
326
327 sub send_digests {
328     my $params = shift;
329
330     PATRON: while ( my ( $borrowernumber, $digest ) = each %{$params->{digests}} ) {
331         next unless defined $digest->{updated} && $digest->{updated} == 1;
332         my $borrower_preferences =
333             C4::Members::Messaging::GetMessagingPreferences(
334                 {
335                     borrowernumber => $borrowernumber,
336                     message_name   => 'auto_renewals'
337                 }
338             );
339
340         next PATRON unless $borrower_preferences; # how could this happen?
341
342         my $patron = Koha::Patrons->find( $borrowernumber );
343         my $branchcode;
344         if ( defined $params->{branchcode} ) {
345             $branchcode = $params->{branchcode};
346         } else {
347             $branchcode = $patron->branchcode;
348         }
349         my $library = Koha::Libraries->find( $branchcode );
350         my $from_address = $library->from_email_address;
351
352         foreach my $transport ( keys %{ $borrower_preferences->{'transports'} } ) {
353             my $letter = C4::Letters::GetPreparedLetter (
354                 module => 'circulation',
355                 letter_code => $params->{letter_code},
356                 branchcode => $branchcode,
357                 lang => $patron->lang,
358                 substitute => {
359                     error => $digest->{error}||0,
360                     success => $digest->{success}||0,
361                     results => $digest->{results},
362                 },
363                 loops => { issues => \@{$digest->{issues}} },
364                 tables      => {
365                     borrowers => $patron->borrowernumber,
366                 },
367                 message_transport_type => $transport,
368             );
369
370             if ($letter) {
371                 C4::Letters::EnqueueLetter(
372                     {
373                         letter                 => $letter,
374                         borrowernumber         => $borrowernumber,
375                         from_address           => $from_address,
376                         message_transport_type => $transport
377                     }
378                 );
379             }
380             else {
381                 warn
382 "no letter of type '$params->{letter_code}' found for borrowernumber $borrowernumber. Please see sample_notices.sql";
383             }
384
385         }
386     }
387 }