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