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