Bug 5549 : Fix calculation of duedates in fines.pl and advance_notices.pl
[koha.git] / misc / cronjobs / fines.pl
1 #!/usr/bin/perl
2
3 #  This script loops through each overdue item, determines the fine,
4 #  and updates the total amount of fines due by each user.  It relies on
5 #  the existence of /tmp/fines, which is created by ???
6 # Doesnt really rely on it, it relys on being able to write to /tmp/
7 # It creates the fines file
8 #
9 #  This script is meant to be run nightly out of cron.
10
11 # Copyright 2000-2002 Katipo Communications
12 #
13 # This file is part of Koha.
14 #
15 # Koha is free software; you can redistribute it and/or modify it under the
16 # terms of the GNU General Public License as published by the Free Software
17 # Foundation; either version 2 of the License, or (at your option) any later
18 # version.
19 #
20 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
21 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
22 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License along
25 # with Koha; if not, write to the Free Software Foundation, Inc.,
26 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27
28
29 # FIXME: use FinesMode as described or change syspref description
30 use strict;
31 #use warnings; FIXME - Bug 2505
32
33 BEGIN {
34     # find Koha's Perl modules
35     # test carefully before changing this
36     use FindBin;
37     eval { require "$FindBin::Bin/kohalib.pl" };
38 }
39
40 #use Date::Calc qw/Date_to_Days/;
41
42 use C4::Context;
43 use C4::Circulation;
44 use C4::Overdues;
45 use C4::Biblio;
46 use C4::Debug;  # supplying $debug and $cgi_debug
47 use Getopt::Long;
48
49 use Koha::Calendar;
50 use Koha::DateUtils;
51
52
53 my $help = 0;
54 my $verbose = 0;
55 my $output_dir;
56
57 GetOptions( 'h|help'    => \$help,
58             'v|verbose' => \$verbose,
59             'o|out:s'   => \$output_dir,
60     );
61 my $usage = << 'ENDUSAGE';
62
63 This script calculates and charges overdue fines
64 to patron accounts.  If the Koha System Preference
65 'finesMode' is set to 'production', the fines are charged
66 to the patron accounts.  If set to 'test', the fines are
67 calculated but not applied.
68
69 This script has the following parameters :
70     -h --help: this message
71     -o --out:  ouput directory for logs (defaults to env or /tmp if !exist)
72     -v --verbose
73
74 ENDUSAGE
75
76 die $usage if $help;
77
78 use vars qw(@borrower_fields @item_fields @other_fields);
79 use vars qw($fldir $libname $control $mode $delim $dbname );
80 use vars qw($filename);
81
82 CHECK {
83     @borrower_fields = qw(cardnumber categorycode surname firstname email phone address citystate);
84         @item_fields = qw(itemnumber barcode date_due);
85        @other_fields = qw(type days_overdue fine);
86     $libname = C4::Context->preference('LibraryName');
87     $control = C4::Context->preference('CircControl');
88     $mode    = C4::Context->preference('finesMode');
89     $dbname  = C4::Context->config('database');
90     $delim   = "\t"; # ?  C4::Context->preference('delimiter') || "\t";
91
92 }
93
94 INIT {
95     $debug and print "Each line will contain the following fields:\n",
96         "From borrowers : ", join(', ', @borrower_fields), "\n",
97         "From items : ", join(', ', @item_fields), "\n",
98         "Per overdue: ", join(', ', @other_fields), "\n",
99         "Delimiter: '$delim'\n";
100 }
101
102 my $data = Getoverdues();
103 my $overdueItemsCounted = 0;
104 my %calendars = ();
105 my $today = DateTime->now( time_zone => C4::Context->tz() );
106 if($output_dir){
107     $fldir = $output_dir if( -d $output_dir );
108 } else {
109     $fldir = $ENV{TMPDIR} || "/tmp";
110 }
111 if (!-d $fldir) {
112     warn "Could not write to $fldir ... does not exist!";
113 }
114 $filename = $dbname;
115 $filename =~ s/\W//;
116 $filename = $fldir . '/'. $filename . '_' .  $today->ymd() . ".log";
117 print "writing to $filename\n" if $verbose;
118 open (FILE, ">$filename") or die "Cannot write file $filename: $!";
119 print FILE join $delim, (@borrower_fields, @item_fields, @other_fields);
120 print FILE "\n";
121
122 for (my $i=0; $i<scalar(@$data); $i++) {
123     my $datedue = dt_from_string($data->[$i]->{'date_due'});
124     unless (defined $data->[$i]->{'borrowernumber'}) {
125         print STDERR "ERROR in Getoverdues line $i: issues.borrowernumber IS NULL.  Repair 'issues' table now!  Skipping record.\n";
126         next;   # Note: this doesn't solve everything.  After NULL borrowernumber, multiple issues w/ real borrowernumbers can pile up.
127     }
128     my $borrower = BorType($data->[$i]->{'borrowernumber'});
129     my $branchcode = ($control eq 'ItemHomeLibrary') ? $data->[$i]->{homebranch} :
130                      ($control eq 'PatronLibrary'  ) ?   $borrower->{branchcode} :
131                                                        $data->[$i]->{branchcode} ;
132     # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here).
133     my $calendar;
134     unless (defined ($calendars{$branchcode})) {
135         $calendars{$branchcode} = Koha::Calendar->new(branchcode => $branchcode);
136     }
137     $calendar = $calendars{$branchcode};
138     my $isHoliday = $calendar->is_holiday($today);
139       
140     if ( DateTime->compare($datedue, $today) != 1) {
141         next; # not overdue
142     }
143
144     $overdueItemsCounted++;
145     my ($amount,$type,$daycounttotal)=
146                 CalcFine($data->[$i], $borrower->{'categorycode'}, $branchcode, $datedue, $today);
147         # FIXME: $type NEVER gets populated by anything.
148     $type ||= '';
149         # Don't update the fine if today is a holiday.  
150         # This ensures that dropbox mode will remove the correct amount of fine.
151         if ($mode eq 'production' and  ! $isHoliday) {
152                 UpdateFine($data->[$i]->{'itemnumber'},$data->[$i]->{'borrowernumber'},$amount,$type,output_pref($datedue)) if( $amount > 0 ) ;
153         }
154     my @cells = ();
155     push @cells, map {$borrower->{$_}} @borrower_fields;
156     push @cells, map {$data->[$i]->{$_}} @item_fields;
157     push @cells, $type, $daycounttotal, $amount;
158     print FILE join($delim, @cells), "\n";
159 }
160
161 my $numOverdueItems = scalar(@$data);
162 if ($verbose) {
163    print <<EOM;
164 Fines assessment -- $today->ymd() -- Saved to $filename
165 Number of Overdue Items:
166      counted $overdueItemsCounted
167     reported $numOverdueItems
168
169 EOM
170 }
171
172 close FILE;