Bug 2389: Add --test switch to overdue_notices.pl
[koha.git] / misc / cronjobs / overdue_notices.pl
1 #!/usr/bin/perl
2
3 # Copyright 2008 Liblime
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 BEGIN {
24
25     # find Koha's Perl modules
26     # test carefully before changing this
27     use FindBin;
28     eval { require "$FindBin::Bin/../kohalib.pl" };
29 }
30
31 use Getopt::Long;
32 use Pod::Usage;
33 use Text::CSV_XS;
34 use DateTime;
35 use DateTime::Duration;
36
37 use C4::Context;
38 use C4::Letters;
39 use C4::Overdues qw(GetFine GetOverdueMessageTransportTypes parse_overdues_letter);
40 use C4::Log;
41 use Koha::Patron::Debarments qw(AddUniqueDebarment);
42 use Koha::DateUtils;
43 use Koha::Calendar;
44 use Koha::Libraries;
45 use Koha::Acquisition::Currencies;
46
47 =head1 NAME
48
49 overdue_notices.pl - prepare messages to be sent to patrons for overdue items
50
51 =head1 SYNOPSIS
52
53 overdue_notices.pl
54   [ -n ][ -library <branchcode> ][ -library <branchcode> ... ]
55   [ -max <number of days> ][ -csv [<filename>] ][ -itemscontent <field list> ]
56   [ -email <email_type> ... ]
57
58  Options:
59    -help                          brief help message
60    -man                           full documentation
61    -v                             verbose
62    -n                             No email will be sent
63    -max          <days>           maximum days overdue to deal with
64    -library      <branchname>     only deal with overdues from this library (repeatable : several libraries can be given)
65    -csv          <filename>       populate CSV file
66    -html         <directory>      Output html to a file in the given directory
67    -text         <directory>      Output plain text to a file in the given directory
68    -itemscontent <list of fields> item information in templates
69    -borcat       <categorycode>   category code that must be included
70    -borcatout    <categorycode>   category code that must be excluded
71    -t                             only include triggered overdues
72    -list-all                      list all overdues
73    -date         <yyyy-mm-dd>     emulate overdues run for this date
74    -email        <email_type>     type of email that will be used. Can be 'email', 'emailpro' or 'B_email'. Repeatable.
75
76 =head1 OPTIONS
77
78 =over 8
79
80 =item B<-help>
81
82 Print a brief help message and exits.
83
84 =item B<-man>
85
86 Prints the manual page and exits.
87
88 =item B<-v>
89
90 Verbose. Without this flag set, only fatal errors are reported.
91
92 =item B<-n>
93
94 Do not send any email. Overdue notices that would have been sent to
95 the patrons or to the admin are printed to standard out. CSV data (if
96 the -csv flag is set) is written to standard out or to any csv
97 filename given.
98
99 =item B<-max>
100
101 Items older than max days are assumed to be handled somewhere else,
102 probably the F<longoverdues.pl> script. They are therefore ignored by
103 this program. No notices are sent for them, and they are not added to
104 any CSV files. Defaults to 90 to match F<longoverdues.pl>.
105
106 =item B<-library>
107
108 select overdues for one specific library. Use the value in the
109 branches.branchcode table. This option can be repeated in order 
110 to select overdues for a group of libraries.
111
112 =item B<-csv>
113
114 Produces CSV data. if -n (no mail) flag is set, then this CSV data is
115 sent to standard out or to a filename if provided. Otherwise, only
116 overdues that could not be emailed are sent in CSV format to the admin.
117
118 =item B<-html>
119
120 Produces html data. If patron does not have an email address or
121 -n (no mail) flag is set, an HTML file is generated in the specified
122 directory. This can be downloaded or further processed by library staff.
123 The file will be called notices-YYYY-MM-DD.html and placed in the directory
124 specified.
125
126 =item B<-text>
127
128 Produces plain text data. If patron does not have an email address or
129 -n (no mail) flag is set, a text file is generated in the specified
130 directory. This can be downloaded or further processed by library staff.
131 The file will be called notices-YYYY-MM-DD.txt and placed in the directory
132 specified.
133
134 =item B<-itemscontent>
135
136 comma separated list of fields that get substituted into templates in
137 places of the E<lt>E<lt>items.contentE<gt>E<gt> placeholder. This
138 defaults to due date,title,barcode,author
139
140 Other possible values come from fields in the biblios, items and
141 issues tables.
142
143 =item B<-borcat>
144
145 Repeatable field, that permits to select only some patron categories.
146
147 =item B<-borcatout>
148
149 Repeatable field, that permits to exclude some patron categories.
150
151 =item B<-t> | B<--triggered>
152
153 This option causes a notice to be generated if and only if 
154 an item is overdue by the number of days defined in a notice trigger.
155
156 By default, a notice is sent each time the script runs, which is suitable for 
157 less frequent run cron script, but requires syncing notice triggers with 
158 the  cron schedule to ensure proper behavior.
159 Add the --triggered option for daily cron, at the risk of no notice 
160 being generated if the cron fails to run on time.
161
162 =item B<-list-all>
163
164 Default items.content lists only those items that fall in the 
165 range of the currently processing notice.
166 Choose list-all to include all overdue items in the list (limited by B<-max> setting).
167
168 =item B<-date>
169
170 use it in order to send overdues on a specific date and not Now. Format: YYYY-MM-DD.
171
172 =item B<-email>
173
174 Allows to specify which type of email will be used. Can be email, emailpro or B_email. Repeatable.
175
176 =back
177
178 =head1 DESCRIPTION
179
180 This script is designed to alert patrons and administrators of overdue
181 items.
182
183 =head2 Configuration
184
185 This script pays attention to the overdue notice configuration
186 performed in the "Overdue notice/status triggers" section of the
187 "Tools" area of the staff interface to Koha. There, you can choose
188 which letter templates are sent out after a configurable number of
189 days to patrons of each library. More information about the use of this
190 section of Koha is available in the Koha manual.
191
192 The templates used to craft the emails are defined in the "Tools:
193 Notices" section of the staff interface to Koha.
194
195 =head2 Outgoing emails
196
197 Typically, messages are prepared for each patron with overdue
198 items. Messages for whom there is no email address on file are
199 collected and sent as attachments in a single email to each library
200 administrator, or if that is not set, then to the email address in the
201 C<KohaAdminEmailAddress> system preference.
202
203 These emails are staged in the outgoing message queue, as are messages
204 produced by other features of Koha. This message queue must be
205 processed regularly by the
206 F<misc/cronjobs/process_message_queue.pl> program.
207
208 In the event that the C<-n> flag is passed to this program, no emails
209 are sent. Instead, messages are sent on standard output from this
210 program. They may be redirected to a file if desired.
211
212 =head2 Templates
213
214 Templates can contain variables enclosed in double angle brackets like
215 E<lt>E<lt>thisE<gt>E<gt>. Those variables will be replaced with values
216 specific to the overdue items or relevant patron. Available variables
217 are:
218
219 =over
220
221 =item E<lt>E<lt>bibE<gt>E<gt>
222
223 the name of the library
224
225 =item E<lt>E<lt>items.contentE<gt>E<gt>
226
227 one line for each item, each line containing a tab separated list of
228 title, author, barcode, issuedate
229
230 =item E<lt>E<lt>borrowers.*E<gt>E<gt>
231
232 any field from the borrowers table
233
234 =item E<lt>E<lt>branches.*E<gt>E<gt>
235
236 any field from the branches table
237
238 =back
239
240 =head2 CSV output
241
242 The C<-csv> command line option lets you specify a file to which
243 overdues data should be output in CSV format.
244
245 With the C<-n> flag set, data about all overdues is written to the
246 file. Without that flag, only information about overdues that were
247 unable to be sent directly to the patrons will be written. In other
248 words, this CSV file replaces the data that is typically sent to the
249 administrator email address.
250
251 =head1 USAGE EXAMPLES
252
253 C<overdue_notices.pl> - In this most basic usage, with no command line
254 arguments, all libraries are processed individually, and notices are
255 prepared for all patrons with overdue items for whom we have email
256 addresses. Messages for those patrons for whom we have no email
257 address are sent in a single attachment to the library administrator's
258 email address, or to the address in the KohaAdminEmailAddress system
259 preference.
260
261 C<overdue_notices.pl -n -csv /tmp/overdues.csv> - sends no email and
262 populates F</tmp/overdues.csv> with information about all overdue
263 items.
264
265 C<overdue_notices.pl -library MAIN max 14> - prepare notices of
266 overdues in the last 2 weeks for the MAIN library.
267
268 =head1 SEE ALSO
269
270 The F<misc/cronjobs/advance_notices.pl> program allows you to send
271 messages to patrons in advance of their items becoming due, or to
272 alert them of items that have just become due.
273
274 =cut
275
276 # These variables are set by command line options.
277 # They are initially set to default values.
278 my $dbh = C4::Context->dbh();
279 my $help    = 0;
280 my $man     = 0;
281 my $verbose = 0;
282 my $nomail  = 0;
283 my $MAX     = 90;
284 my $test_mode = 0;
285 my @branchcodes; # Branch(es) passed as parameter
286 my @emails_to_use;    # Emails to use for messaging
287 my @emails;           # Emails given in command-line parameters
288 my $csvfilename;
289 my $htmlfilename;
290 my $text_filename;
291 my $triggered = 0;
292 my $listall = 0;
293 my $itemscontent = join( ',', qw( date_due title barcode author itemnumber ) );
294 my @myborcat;
295 my @myborcatout;
296 my ( $date_input, $today );
297
298 GetOptions(
299     'help|?'         => \$help,
300     'man'            => \$man,
301     'v'              => \$verbose,
302     'n'              => \$nomail,
303     'max=s'          => \$MAX,
304     'library=s'      => \@branchcodes,
305     'csv:s'          => \$csvfilename,    # this optional argument gets '' if not supplied.
306     'html:s'         => \$htmlfilename,    # this optional argument gets '' if not supplied.
307     'text:s'         => \$text_filename,    # this optional argument gets '' if not supplied.
308     'itemscontent=s' => \$itemscontent,
309     'list-all'       => \$listall,
310     't|triggered'    => \$triggered,
311     'test'           => \$test_mode,
312     'date=s'         => \$date_input,
313     'borcat=s'       => \@myborcat,
314     'borcatout=s'    => \@myborcatout,
315     'email=s'        => \@emails,
316 ) or pod2usage(2);
317 pod2usage(1) if $help;
318 pod2usage( -verbose => 2 ) if $man;
319
320 cronlogaction() unless $test_mode;
321
322 if ( defined $csvfilename && $csvfilename =~ /^-/ ) {
323     warn qq(using "$csvfilename" as filename, that seems odd);
324 }
325
326 my @overduebranches    = C4::Overdues::GetBranchcodesWithOverdueRules();        # Branches with overdue rules
327 my @branches;                                                                   # Branches passed as parameter with overdue rules
328 my $branchcount = scalar(@overduebranches);
329
330 my $overduebranch_word = scalar @overduebranches > 1 ? 'branches' : 'branch';
331 my $branchcodes_word = scalar @branchcodes > 1 ? 'branches' : 'branch';
332
333 my $PrintNoticesMaxLines = C4::Context->preference('PrintNoticesMaxLines');
334
335 if ($branchcount) {
336     $verbose and warn "Found $branchcount $overduebranch_word with first message enabled: " . join( ', ', map { "'$_'" } @overduebranches ), "\n";
337 } else {
338     die 'No branches with active overduerules';
339 }
340
341 if (@branchcodes) {
342     $verbose and warn "$branchcodes_word @branchcodes passed on parameter\n";
343     
344     # Getting libraries which have overdue rules
345     my %seen = map { $_ => 1 } @branchcodes;
346     @branches = grep { $seen{$_} } @overduebranches;
347     
348     
349     if (@branches) {
350
351         my $branch_word = scalar @branches > 1 ? 'branches' : 'branch';
352         $verbose and warn "$branch_word @branches have overdue rules\n";
353
354     } else {
355     
356         $verbose and warn "No active overduerules for $branchcodes_word  '@branchcodes'\n";
357         ( scalar grep { '' eq $_ } @branches )
358           or die "No active overduerules for DEFAULT either!";
359         $verbose and warn "Falling back on default rules for @branchcodes\n";
360         @branches = ('');
361     }
362 }
363 my $date_to_run;
364 my $date;
365 if ( $date_input ){
366     eval {
367         $date_to_run = dt_from_string( $date_input, 'iso' );
368     };
369     die "$date_input is not a valid date, aborting! Use a date in format YYYY-MM-DD."
370         if $@ or not $date_to_run;
371
372     # It's certainly useless to escape $date_input
373     # dt_from_string should not return something if $date_input is not correctly set.
374     $date = $dbh->quote( $date_input );
375 }
376 else {
377     $date="NOW()";
378     $date_to_run = dt_from_string();
379 }
380
381 # these are the fields that will be substituted into <<item.content>>
382 my @item_content_fields = split( /,/, $itemscontent );
383
384 binmode( STDOUT, ':encoding(UTF-8)' );
385
386
387 our $csv;       # the Text::CSV_XS object
388 our $csv_fh;    # the filehandle to the CSV file.
389 if ( defined $csvfilename ) {
390     my $sep_char = C4::Context->preference('delimiter') || ';';
391     $sep_char = "\t" if ($sep_char eq 'tabulation');
392     $csv = Text::CSV_XS->new( { binary => 1 , sep_char => $sep_char } );
393     if ( $csvfilename eq '' ) {
394         $csv_fh = *STDOUT;
395     } else {
396         open $csv_fh, ">", $csvfilename or die "unable to open $csvfilename: $!";
397     }
398     if ( $csv->combine(qw(name surname address1 address2 zipcode city country email phone cardnumber itemcount itemsinfo branchname letternumber)) ) {
399         print $csv_fh $csv->string, "\n";
400     } else {
401         $verbose and warn 'combine failed on argument: ' . $csv->error_input;
402     }
403 }
404
405 @branches = @overduebranches unless @branches;
406 our $fh;
407 if ( defined $htmlfilename ) {
408   if ( $htmlfilename eq '' ) {
409     $fh = *STDOUT;
410   } else {
411     my $today = DateTime->now(time_zone => C4::Context->tz );
412     open $fh, ">:encoding(UTF-8)",File::Spec->catdir ($htmlfilename,"notices-".$today->ymd().".html");
413   }
414   
415   print $fh "<html>\n";
416   print $fh "<head>\n";
417   print $fh "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
418   print $fh "<style type='text/css'>\n";
419   print $fh "pre {page-break-after: always;}\n";
420   print $fh "pre {white-space: pre-wrap;}\n";
421   print $fh "pre {white-space: -moz-pre-wrap;}\n";
422   print $fh "pre {white-space: -o-pre-wrap;}\n";
423   print $fh "pre {word-wrap: break-work;}\n";
424   print $fh "</style>\n";
425   print $fh "</head>\n";
426   print $fh "<body>\n";
427 }
428 elsif ( defined $text_filename ) {
429   if ( $text_filename eq '' ) {
430     $fh = *STDOUT;
431   } else {
432     my $today = DateTime->now(time_zone => C4::Context->tz );
433     open $fh, ">",File::Spec->catdir ($text_filename,"notices-".$today->ymd().".txt");
434   }
435 }
436
437 foreach my $branchcode (@branches) {
438     if ( C4::Context->preference('OverdueNoticeCalendar') ) {
439         my $calendar = Koha::Calendar->new( branchcode => $branchcode );
440         if ( $calendar->is_holiday($date_to_run) ) {
441             next;
442         }
443     }
444
445     my $library             = Koha::Libraries->find($branchcode);
446     my $admin_email_address = $library->branchemail
447       || C4::Context->preference('KohaAdminEmailAddress');
448     my @output_chunks;    # may be sent to mail or stdout or csv file.
449
450     $verbose and warn sprintf "branchcode : '%s' using %s\n", $branchcode, $admin_email_address;
451
452     my $sth2 = $dbh->prepare( <<"END_SQL" );
453 SELECT biblio.*, items.*, issues.*, biblioitems.itemtype, branchname
454   FROM issues,items,biblio, biblioitems, branches b
455   WHERE items.itemnumber=issues.itemnumber
456     AND biblio.biblionumber   = items.biblionumber
457     AND b.branchcode = items.homebranch
458     AND biblio.biblionumber   = biblioitems.biblionumber
459     AND issues.borrowernumber = ?
460     AND TO_DAYS($date)-TO_DAYS(issues.date_due) >= 0
461 END_SQL
462
463     my $query = "SELECT * FROM overduerules WHERE delay1 IS NOT NULL AND branchcode = ? ";
464     $query .= " AND categorycode IN (".join( ',' , ('?') x @myborcat ).") " if (@myborcat);
465     $query .= " AND categorycode NOT IN (".join( ',' , ('?') x @myborcatout ).") " if (@myborcatout);
466     
467     my $rqoverduerules =  $dbh->prepare($query);
468     $rqoverduerules->execute($branchcode, @myborcat, @myborcatout);
469     
470     # We get default rules is there is no rule for this branch
471     if($rqoverduerules->rows == 0){
472         $query = "SELECT * FROM overduerules WHERE delay1 IS NOT NULL AND branchcode = '' ";
473         $query .= " AND categorycode IN (".join( ',' , ('?') x @myborcat ).") " if (@myborcat);
474         $query .= " AND categorycode NOT IN (".join( ',' , ('?') x @myborcatout ).") " if (@myborcatout);
475         
476         $rqoverduerules = $dbh->prepare($query);
477         $rqoverduerules->execute(@myborcat, @myborcatout);
478     }
479
480     # my $outfile = 'overdues_' . ( $mybranch || $branchcode || 'default' );
481     while ( my $overdue_rules = $rqoverduerules->fetchrow_hashref ) {
482       PERIOD: foreach my $i ( 1 .. 3 ) {
483
484             $verbose and warn "branch '$branchcode', categorycode = $overdue_rules->{categorycode} pass $i\n";
485
486             my $mindays = $overdue_rules->{"delay$i"};    # the notice will be sent after mindays days (grace period)
487             my $maxdays = (
488                   $overdue_rules->{ "delay" . ( $i + 1 ) }
489                 ? $overdue_rules->{ "delay" . ( $i + 1 ) } - 1
490                 : ($MAX)
491             );                                            # issues being more than maxdays late are managed somewhere else. (borrower probably suspended)
492
493             next unless defined $mindays;
494
495             if ( !$overdue_rules->{"letter$i"} ) {
496                 $verbose and warn "No letter$i code for branch '$branchcode'";
497                 next PERIOD;
498             }
499
500             # $letter->{'content'} is the text of the mail that is sent.
501             # this text contains fields that are replaced by their value. Those fields must be written between brackets
502             # The following fields are available :
503             # itemcount is interpreted here as the number of items in the overdue range defined by the current notice or all overdues < max if(-list-all).
504             # <date> <itemcount> <firstname> <lastname> <address1> <address2> <address3> <city> <postcode> <country>
505
506             my $borrower_sql = <<"END_SQL";
507 SELECT issues.borrowernumber, firstname, surname, address, address2, city, zipcode, country, email, emailpro, B_email, smsalertnumber, phone, cardnumber, date_due
508 FROM   issues,borrowers,categories
509 WHERE  issues.borrowernumber=borrowers.borrowernumber
510 AND    borrowers.categorycode=categories.categorycode
511 AND    TO_DAYS($date)-TO_DAYS(issues.date_due) >= 0
512 END_SQL
513             my @borrower_parameters;
514             if ($branchcode) {
515                 $borrower_sql .= ' AND issues.branchcode=? ';
516                 push @borrower_parameters, $branchcode;
517             }
518             if ( $overdue_rules->{categorycode} ) {
519                 $borrower_sql .= ' AND borrowers.categorycode=? ';
520                 push @borrower_parameters, $overdue_rules->{categorycode};
521             }
522             $borrower_sql .= '  AND categories.overduenoticerequired=1 ORDER BY issues.borrowernumber';
523
524             # $sth gets borrower info iff at least one overdue item has triggered the overdue action.
525                 my $sth = $dbh->prepare($borrower_sql);
526             $sth->execute(@borrower_parameters);
527
528             $verbose and warn $borrower_sql . "\n $branchcode | " . $overdue_rules->{'categorycode'} . "\n ($mindays, $maxdays, ".  $date_to_run->datetime() .")\nreturns " . $sth->rows . " rows";
529             my $borrowernumber;
530             while ( my $data = $sth->fetchrow_hashref ) {
531
532                 # check the borrower has at least one item that matches
533                 my $days_between;
534                 if ( C4::Context->preference('OverdueNoticeCalendar') )
535                 {
536                     my $calendar =
537                       Koha::Calendar->new( branchcode => $branchcode );
538                     $days_between =
539                       $calendar->days_between( dt_from_string($data->{date_due}),
540                         $date_to_run );
541                 }
542                 else {
543                     $days_between =
544                       $date_to_run->delta_days( dt_from_string($data->{date_due}) );
545                 }
546                 $days_between = $days_between->in_units('days');
547                 if ($triggered) {
548                     if ( $mindays != $days_between ) {
549                         next;
550                     }
551                 }
552                 else {
553                     unless (   $days_between >= $mindays
554                         && $days_between <= $maxdays )
555                     {
556                         next;
557                     }
558                 }
559                 if (defined $borrowernumber && $borrowernumber eq $data->{'borrowernumber'}){
560 # we have already dealt with this borrower
561                     $verbose and warn "already dealt with this borrower $borrowernumber";
562                     next;
563                 }
564                 $borrowernumber = $data->{'borrowernumber'};
565                 my $borr =
566                     $data->{'firstname'} . ', '
567                   . $data->{'surname'} . ' ('
568                   . $borrowernumber . ')';
569                 $verbose
570                   and warn "borrower $borr has items triggering level $i.";
571
572                 @emails_to_use = ();
573                 my $notice_email =
574                     C4::Members::GetNoticeEmailAddress($borrowernumber);
575                 unless ($nomail) {
576                     if (@emails) {
577                         foreach (@emails) {
578                             push @emails_to_use, $data->{$_} if ( $data->{$_} );
579                         }
580                     }
581                     else {
582                         push @emails_to_use, $notice_email if ($notice_email);
583                     }
584                 }
585
586                 my $letter = C4::Letters::getletter( 'circulation', $overdue_rules->{"letter$i"}, $branchcode );
587
588                 unless ($letter) {
589                     $verbose and warn qq|Message '$overdue_rules->{"letter$i"}' content not found|;
590
591                     # might as well skip while PERIOD, no other borrowers are going to work.
592                     # FIXME : Does this mean a letter must be defined in order to trigger a debar ?
593                     next PERIOD;
594                 }
595     
596                 if ( $overdue_rules->{"debarred$i"} ) {
597     
598                     #action taken is debarring
599                     AddUniqueDebarment(
600                         {
601                             borrowernumber => $borrowernumber,
602                             type           => 'OVERDUES',
603                             comment => "OVERDUES_PROCESS " .  output_pref( dt_from_string() ),
604                         }
605                     ) unless $test_mode;
606                     $verbose and warn "debarring $borr\n";
607                 }
608                 my @params = ($borrowernumber);
609                 $verbose and warn "STH2 PARAMS: borrowernumber = $borrowernumber";
610
611                 $sth2->execute(@params);
612                 my $itemcount = 0;
613                 my $titles = "";
614                 my @items = ();
615                 
616                 my $j = 0;
617                 my $exceededPrintNoticesMaxLines = 0;
618                 while ( my $item_info = $sth2->fetchrow_hashref() ) {
619                     if ( C4::Context->preference('OverdueNoticeCalendar') ) {
620                         my $calendar =
621                           Koha::Calendar->new( branchcode => $branchcode );
622                         $days_between =
623                           $calendar->days_between(
624                             dt_from_string( $item_info->{date_due} ), $date_to_run );
625                     }
626                     else {
627                         $days_between =
628                           $date_to_run->delta_days(
629                             dt_from_string( $item_info->{date_due} ) );
630                     }
631                     $days_between = $days_between->in_units('days');
632                     if ($listall){
633                         unless ($days_between >= 1 and $days_between <= $MAX){
634                             next;
635                         }
636                     }
637                     else {
638                         if ($triggered) {
639                             if ( $mindays != $days_between ) {
640                                 next;
641                             }
642                         }
643                         else {
644                             unless ( $days_between >= $mindays
645                                 && $days_between <= $maxdays )
646                             {
647                                 next;
648                             }
649                         }
650                     }
651
652                     if ( ( scalar(@emails_to_use) == 0 || $nomail ) && $PrintNoticesMaxLines && $j >= $PrintNoticesMaxLines ) {
653                       $exceededPrintNoticesMaxLines = 1;
654                       last;
655                     }
656                     $j++;
657                     my @item_info = map { $_ =~ /^date|date$/ ?
658                                            eval { output_pref( { dt => dt_from_string( $item_info->{$_} ), dateonly => 1 } ); }
659                                            :
660                                            $item_info->{$_} || '' } @item_content_fields;
661                     $titles .= join("\t", @item_info) . "\n";
662                     $itemcount++;
663                     push @items, $item_info;
664                 }
665                 $sth2->finish;
666
667                 my @message_transport_types = @{ GetOverdueMessageTransportTypes( $branchcode, $overdue_rules->{categorycode}, $i) };
668                 @message_transport_types = @{ GetOverdueMessageTransportTypes( q{}, $overdue_rules->{categorycode}, $i) }
669                     unless @message_transport_types;
670
671
672                 my $print_sent = 0; # A print notice is not yet sent for this patron
673                 for my $mtt ( @message_transport_types ) {
674                     my $effective_mtt = $mtt;
675                     if ( ($mtt eq 'email' and not scalar @emails_to_use) or ($mtt eq 'sms' and not $data->{smsalertnumber}) ) {
676                         # email or sms is requested but not exist, do a print.
677                         $effective_mtt = 'print';
678                     }
679
680                     my $letter_exists = C4::Letters::getletter( 'circulation', $overdue_rules->{"letter$i"}, $branchcode, $effective_mtt ) ? 1 : 0;
681                     my $letter = parse_overdues_letter(
682                         {   letter_code     => $overdue_rules->{"letter$i"},
683                             borrowernumber  => $borrowernumber,
684                             branchcode      => $branchcode,
685                             items           => \@items,
686                             substitute      => {    # this appears to be a hack to overcome incomplete features in this code.
687                                                 bib             => $library->branchname, # maybe 'bib' is a typo for 'lib<rary>'?
688                                                 'items.content' => $titles,
689                                                 'count'         => $itemcount,
690                                                },
691                             # If there is no template defined for the requested letter
692                             # Fallback on email
693                             message_transport_type => $letter_exists ? $effective_mtt : 'email',
694                         }
695                     );
696                     unless ($letter) {
697                         $verbose and warn qq|Message '$overdue_rules->{"letter$i"}' content not found|;
698                         # this transport doesn't have a configured notice, so try another
699                         next;
700                     }
701
702                     if ( $exceededPrintNoticesMaxLines ) {
703                       $letter->{'content'} .= "List too long for form; please check your account online for a complete list of your overdue items.";
704                     }
705
706                     my @misses = grep { /./ } map { /^([^>]*)[>]+/; ( $1 || '' ); } split /\</, $letter->{'content'};
707                     if (@misses) {
708                         $verbose and warn "The following terms were not matched and replaced: \n\t" . join "\n\t", @misses;
709                     }
710
711                     if ($nomail) {
712                         push @output_chunks,
713                           prepare_letter_for_printing(
714                           {   letter         => $letter,
715                               borrowernumber => $borrowernumber,
716                               firstname      => $data->{'firstname'},
717                               lastname       => $data->{'surname'},
718                               address1       => $data->{'address'},
719                               address2       => $data->{'address2'},
720                               city           => $data->{'city'},
721                               phone          => $data->{'phone'},
722                               cardnumber     => $data->{'cardnumber'},
723                               branchname     => $library->branchname,
724                               letternumber   => $i,
725                               postcode       => $data->{'zipcode'},
726                               country        => $data->{'country'},
727                               email          => $notice_email,
728                               itemcount      => $itemcount,
729                               titles         => $titles,
730                               outputformat   => defined $csvfilename ? 'csv' : defined $htmlfilename ? 'html' : defined $text_filename ? 'text' : '',
731                             }
732                           );
733                     } else {
734                         if ( ($mtt eq 'email' and not scalar @emails_to_use) or ($mtt eq 'sms' and not $data->{smsalertnumber}) ) {
735                             push @output_chunks,
736                               prepare_letter_for_printing(
737                               {   letter         => $letter,
738                                   borrowernumber => $borrowernumber,
739                                   firstname      => $data->{'firstname'},
740                                   lastname       => $data->{'surname'},
741                                   address1       => $data->{'address'},
742                                   address2       => $data->{'address2'},
743                                   city           => $data->{'city'},
744                                   postcode       => $data->{'zipcode'},
745                                   country        => $data->{'country'},
746                                   email          => $notice_email,
747                                   itemcount      => $itemcount,
748                                   titles         => $titles,
749                                   outputformat   => defined $csvfilename ? 'csv' : defined $htmlfilename ? 'html' : defined $text_filename ? 'text' : '',
750                                 }
751                               );
752                         }
753                         unless ( $effective_mtt eq 'print' and $print_sent == 1 ) {
754                             # Just sent a print if not already done.
755                             C4::Letters::EnqueueLetter(
756                                 {   letter                 => $letter,
757                                     borrowernumber         => $borrowernumber,
758                                     message_transport_type => $effective_mtt,
759                                     from_address           => $admin_email_address,
760                                     to_address             => join(',', @emails_to_use),
761                                 }
762                             ) unless $test_mode;
763                             # A print notice should be sent only once per overdue level.
764                             # Without this check, a print could be sent twice or more if the library checks sms and email and print and the patron has no email or sms number.
765                             $print_sent = 1 if $effective_mtt eq 'print';
766                         }
767                     }
768                 }
769             }
770             $sth->finish;
771         }
772     }
773
774     if (@output_chunks) {
775         if ( defined $csvfilename ) {
776             print $csv_fh @output_chunks;        
777         }
778         elsif ( defined $htmlfilename ) {
779             print $fh @output_chunks;        
780         }
781         elsif ( defined $text_filename ) {
782             print $fh @output_chunks;        
783         }
784         elsif ($nomail){
785                 local $, = "\f";    # pagebreak
786                 print @output_chunks;
787         }
788         # Generate the content of the csv with headers
789         my $content;
790         if ( defined $csvfilename ) {
791             my $delimiter = C4::Context->preference('delimiter') || ';';
792             $content = join($delimiter, qw(title name surname address1 address2 zipcode city country email itemcount itemsinfo due_date issue_date)) . "\n";
793         }
794         else {
795             $content = "";
796         }
797         $content .= join( "\n", @output_chunks );
798
799         my $attachment = {
800             filename => defined $csvfilename ? 'attachment.csv' : 'attachment.txt',
801             type => 'text/plain',
802             content => $content, 
803         };
804
805         my $letter = {
806             title   => 'Overdue Notices',
807             content => 'These messages were not sent directly to the patrons.',
808         };
809         C4::Letters::EnqueueLetter(
810             {   letter                 => $letter,
811                 borrowernumber         => undef,
812                 message_transport_type => 'email',
813                 attachments            => [$attachment],
814                 to_address             => $admin_email_address,
815             }
816         );
817     }
818
819 }
820 if ($csvfilename) {
821     # note that we're not testing on $csv_fh to prevent closing
822     # STDOUT.
823     close $csv_fh;
824 }
825
826 if ( defined $htmlfilename ) {
827   print $fh "</body>\n";
828   print $fh "</html>\n";
829   close $fh;
830 } elsif ( defined $text_filename ) {
831   close $fh;
832 }
833
834 =head1 INTERNAL METHODS
835
836 These methods are internal to the operation of overdue_notices.pl.
837
838 =head2 prepare_letter_for_printing
839
840 returns a string of text appropriate for printing in the event that an
841 overdue notice will not be sent to the patron's email
842 address. Depending on the desired output format, this may be a CSV
843 string, or a human-readable representation of the notice.
844
845 required parameters:
846   letter
847   borrowernumber
848
849 optional parameters:
850   outputformat
851
852 =cut
853
854 sub prepare_letter_for_printing {
855     my $params = shift;
856
857     return unless ref $params eq 'HASH';
858
859     foreach my $required_parameter (qw( letter borrowernumber )) {
860         return unless defined $params->{$required_parameter};
861     }
862
863     my $return;
864     chomp $params->{titles};
865     if ( exists $params->{'outputformat'} && $params->{'outputformat'} eq 'csv' ) {
866         if ($csv->combine(
867                 $params->{'firstname'}, $params->{'lastname'}, $params->{'address1'},  $params->{'address2'}, $params->{'postcode'},
868                 $params->{'city'}, $params->{'country'}, $params->{'email'}, $params->{'phone'}, $params->{'cardnumber'},
869                 $params->{'itemcount'}, $params->{'titles'}, $params->{'branchname'}, $params->{'letternumber'}
870             )
871           ) {
872             return $csv->string, "\n";
873         } else {
874             $verbose and warn 'combine failed on argument: ' . $csv->error_input;
875         }
876     } elsif ( exists $params->{'outputformat'} && $params->{'outputformat'} eq 'html' ) {
877       $return = "<pre>\n";
878       $return .= "$params->{'letter'}->{'content'}\n";
879       $return .= "\n</pre>\n";
880     } else {
881         $return .= "$params->{'letter'}->{'content'}\n";
882
883         # $return .= Data::Dumper->Dump( [ $params->{'borrowernumber'}, $params->{'letter'} ], [qw( borrowernumber letter )] );
884     }
885     return $return;
886 }
887