Bug 6858: Adds staticfines.pl for static fines processing
[koha.git] / misc / cronjobs / staticfines.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 2011-2012 BibLibre
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 use Modern::Perl;
29
30 BEGIN {
31
32     # find Koha's Perl modules
33     # test carefully before changing this
34     use FindBin;
35     eval { require "$FindBin::Bin/kohalib.pl" };
36 }
37
38 use Date::Calc qw/Date_to_Days/;
39
40 use C4::Context;
41 use C4::Circulation;
42 use C4::Overdues;
43 use C4::Calendar qw();    # don't need any exports from Calendar
44 use C4::Biblio;
45 use C4::Debug;            # supplying $debug and $cgi_debug
46 use Getopt::Long;
47 use List::MoreUtils qw/none/;
48
49 my $help    = 0;
50 my $verbose = 0;
51 my @pcategories;
52 my @categories;
53 my %catamounts;
54 my @libraries;
55 my $delay;
56 my $useborrowerlibrary;
57 my $borrowernumberlimit;
58 my $borrowersalreadyapplied; # hashref of borrowers for whom we already applied the fine, so it's only applied once
59 my $debug = $ENV{'DEBUG'} || 0;
60 my $bigdebug = 0;
61
62 GetOptions(
63     'h|help'      => \$help,
64     'v|verbose'   => \$verbose,
65     'c|category:s'=> \@pcategories,
66     'l|library:s' => \@libraries,
67     'd|delay:i'   => \$delay,
68     'u|use-borrower-library' => \$useborrowerlibrary,
69     'b|borrower:i' => \$borrowernumberlimit
70 );
71 my $usage = << 'ENDUSAGE';
72
73 This script calculates and charges overdue fines to patron accounts.
74
75 If the Koha System Preference 'finesMode' is set to 'production', the fines are charged to the patron accounts.
76 If set to 'test', the fines are calculated but not applied.
77
78 Please note that the fines won't be applied on a holiday.
79
80 This script has the following parameters :
81     -h --help: this message
82     -v --verbose
83     -c --category borrower_category,amount (repeatable)
84     -l --library (repeatable)
85     -d --delay
86     -u --use-borrower-library: use borrower's library, regardless of the CircControl syspref
87     -b --borrower borrowernumber: only for one given borrower
88
89 ENDUSAGE
90 die $usage if $help;
91
92 my $dbh = C4::Context->dbh;
93
94 # Processing categories
95 foreach (@pcategories) {
96     my ($category, $amount) = split(',', $_);
97     push @categories, $category;
98     $catamounts{$category} = $amount;
99 }
100
101 use vars qw(@borrower_fields @item_fields @other_fields);
102 use vars qw($fldir $libname $control $mode $delim $dbname $today $today_iso $today_days);
103 use vars qw($filename);
104
105 CHECK {
106     @borrower_fields = qw(cardnumber categorycode surname firstname email phone address citystate);
107     @item_fields     = qw(itemnumber barcode date_due);
108     @other_fields    = qw(type days_overdue fine);
109     $libname         = C4::Context->preference('LibraryName');
110     $control         = C4::Context->preference('CircControl');
111     $mode            = C4::Context->preference('finesMode');
112     $dbname          = C4::Context->config('database');
113     $delim           = "\t";                                                                          # ?  C4::Context->preference('delimiter') || "\t";
114
115 }
116
117 INIT {
118     $debug and print "Each line will contain the following fields:\n",
119       "From borrowers : ", join( ', ', @borrower_fields ), "\n",
120       "From items : ",     join( ', ', @item_fields ),     "\n",
121       "Per overdue: ",     join( ', ', @other_fields ),    "\n",
122       "Delimiter: '$delim'\n";
123 }
124 $debug and (defined $borrowernumberlimit) and print "--borrower limitation: borrower $borrowernumberlimit\n";
125 my $data = (defined $borrowernumberlimit) ? checkoverdues($borrowernumberlimit) : Getoverdues();
126 my $overdueItemsCounted = 0;
127 my %calendars           = ();
128 $today      = C4::Dates->new();
129 $today_iso  = $today->output('iso');
130 $today_days = Date_to_Days( split( /-/, $today_iso ) );
131
132 for ( my $i = 0 ; $i < scalar(@$data) ; $i++ ) {
133     my $datedue;
134     my $datedue_days;
135     eval {
136     $datedue = C4::Dates->new( $data->[$i]->{'date_due'}, 'iso' );
137     $datedue_days = Date_to_Days( split( /-/, $datedue->output('iso') ) );
138     };
139     if ($@) {
140     warn "Error on date for borrower " . $data->[$i]->{'borrowernumber'} .  ": $@date_due: " . $data->[$i]->{'date_due'} . "\ndatedue_days: " . $datedue_days . "\nSkipping";
141     next;
142     }
143     my $due_str = $datedue->output();
144     unless ( defined $data->[$i]->{'borrowernumber'} ) {
145         print STDERR "ERROR in Getoverdues line $i: issues.borrowernumber IS NULL.  Repair 'issues' table now!  Skipping record.\n";
146         next;    # Note: this doesn't solve everything.  After NULL borrowernumber, multiple issues w/ real borrowernumbers can pile up.
147     }
148     my $borrower = BorType( $data->[$i]->{'borrowernumber'} );
149
150     # Skipping borrowers that are not in @categories
151     $bigdebug and warn "Skipping borrower from category " . $borrower->{categorycode} if none { $borrower->{categorycode} eq $_ } @categories;
152     next if none { $borrower->{categorycode} eq $_ } @categories;
153
154     my $branchcode =
155         ( $useborrowerlibrary )           ? $borrower->{branchcode}
156       : ( $control eq 'ItemHomeLibrary' ) ? $data->[$i]->{homebranch}
157       : ( $control eq 'PatronLibrary' )   ? $borrower->{branchcode}
158       :                                     $data->[$i]->{branchcode};
159     # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here).
160
161     # Skipping branchcodes that are not in @libraries
162     $bigdebug and warn "Skipping library $branchcode" if none { $branchcode eq $_ } @libraries;
163     next if none { $branchcode eq $_ } @libraries;
164
165     my $calendar;
166     unless ( defined( $calendars{$branchcode} ) ) {
167         $calendars{$branchcode} = C4::Calendar->new( branchcode => $branchcode );
168     }
169     $calendar = $calendars{$branchcode};
170     my $isHoliday = $calendar->isHoliday( split '/', $today->output('metric') );
171
172     # Reassing datedue_days if -delay specified in commandline
173     $bigdebug and warn "Using commandline supplied delay : $delay" if ($delay);
174     $datedue_days += $delay if ($delay);
175
176     ( $datedue_days <= $today_days ) or next;    # or it's not overdue, right?
177
178     $overdueItemsCounted++;
179     my ( $amount, $type, $daycounttotal, $daycount ) = CalcFine( $data->[$i], $borrower->{'categorycode'}, $branchcode, undef, undef, $datedue, $today );
180
181     # Reassign fine's amount if specified in command-line
182     $amount = $catamounts{$borrower->{'categorycode'}} if (defined $catamounts{$borrower->{'categorycode'}});
183
184     # We check if there is already a fine for the given borrower
185     my $fine = GetFine($data->[$i]->{'borrowernumber'});
186     if ($fine > 0) {
187         $debug and warn "There is already a fine for borrower " . $data->[$i]->{'borrowernumber'} . ". Nothing to do here. Skipping this borrower";
188         next;
189     }
190
191     # FIXME: $type NEVER gets populated by anything.
192     ( defined $type ) or $type = '';
193
194     # Don't update the fine if today is a holiday.
195     # This ensures that dropbox mode will remove the correct amount of fine.
196     if ( $mode eq 'production' and !$borrowersalreadyapplied->{$data->[$i]->{'borrowernumber'}}) {
197         # If we're on a holiday, warn the user (if debug) that no fine will be applied
198         if($isHoliday) {
199             $debug and warn "Today is a holiday. The fine for borrower " . $data->[$i]->{'borrowernumber'} . " will not be applied";
200         } else {
201             $debug and warn "Creating fine for borrower " . $data->[$i]->{'borrowernumber'} . " with amount : $amount";
202
203             # We mark this borrower as already processed
204             $borrowersalreadyapplied->{$data->[$i]->{'borrowernumber'}} = 1;
205
206             my $borrowernumber = $data->[$i]->{'borrowernumber'};
207             my $itemnumber     = $data->[$i]->{'itemnumber'};
208
209             # And we create the fine
210             my $sth4 = $dbh->prepare( "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?" );
211             $sth4->execute($itemnumber);
212             my $title = $sth4->fetchrow;
213
214             my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
215             my $desc        = "staticfine";
216             my $query       = "INSERT INTO accountlines
217                         (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
218                                 VALUES (?,?,now(),?,?,'F',?,?,?)";
219             my $sth2 = $dbh->prepare($query);
220             $bigdebug and warn "query: $query\nw/ args: $borrowernumber, $itemnumber, $amount, $desc, $amount, $amount, $nextaccntno\n";
221             $sth2->execute( $borrowernumber, $itemnumber, $amount, $desc, $amount, $amount, $nextaccntno );
222
223         }
224     }
225 }
226
227 my $numOverdueItems = scalar(@$data);
228 if ($verbose) {
229     print <<EOM;
230 Fines assessment -- $today_iso
231 Number of Overdue Items:
232      counted $overdueItemsCounted
233     reported $numOverdueItems
234
235 EOM
236 }
237