Bug 28617: Remove kohalib.pl and rely on PERL5LIB
[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 # Doesn't really rely on it, it relies 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
16 # under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 3 of the License, or
18 # (at your option) any later version.
19 #
20 # Koha is distributed in the hope that it will be useful, but
21 # WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with Koha; if not, see <http://www.gnu.org/licenses>.
27
28 use Modern::Perl;
29
30 use Date::Calc qw( Date_to_Days );
31
32 use Koha::Script -cron;
33 use C4::Context;
34 use C4::Overdues qw( CalcFine checkoverdues GetFine Getoverdues );
35 use C4::Calendar qw();    # don't need any exports from Calendar
36 use C4::Log qw( cronlogaction );
37 use Getopt::Long qw( GetOptions );
38 use List::MoreUtils qw( none );
39 use Koha::DateUtils qw( dt_from_string output_pref );
40 use Koha::Patrons;
41
42 my $help    = 0;
43 my $verbose = 0;
44 my @pcategories;
45 my @categories;
46 my %catamounts;
47 my @libraries;
48 my $delay;
49 my $useborrowerlibrary;
50 my $borrowernumberlimit;
51 my $borrowersalreadyapplied; # hashref of borrowers for whom we already applied the fine, so it's only applied once
52 my $debug = 0;
53 my $bigdebug = 0;
54
55 GetOptions(
56     'h|help'      => \$help,
57     'v|verbose'   => \$verbose,
58     'c|category:s'=> \@pcategories,
59     'l|library:s' => \@libraries,
60     'd|delay:i'   => \$delay,
61     'u|use-borrower-library' => \$useborrowerlibrary,
62     'b|borrower:i' => \$borrowernumberlimit
63 );
64 my $usage = << 'ENDUSAGE';
65
66 This script calculates and charges overdue fines to patron accounts.
67
68 If the Koha System Preference 'finesMode' is set to 'production', the fines are charged to the patron accounts.
69
70 Please note that the fines won't be applied on a holiday.
71
72 This script has the following parameters :
73     -h --help: this message
74     -v --verbose
75     -c --category borrower_category,amount (repeatable)
76     -l --library (repeatable)
77     -d --delay
78     -u --use-borrower-library: use borrower's library, regardless of the CircControl syspref
79     -b --borrower borrowernumber: only for one given borrower
80
81 ENDUSAGE
82 die $usage if $help;
83
84 cronlogaction();
85
86 my $dbh = C4::Context->dbh;
87
88 # Processing categories
89 foreach (@pcategories) {
90     my ($category, $amount) = split(',', $_);
91     push @categories, $category;
92     $catamounts{$category} = $amount;
93 }
94
95 use vars qw(@borrower_fields @item_fields @other_fields);
96 use vars qw($fldir $libname $control $mode $delim $dbname $today $today_iso $today_days);
97 use vars qw($filename);
98
99 CHECK {
100     @borrower_fields = qw(cardnumber categorycode surname firstname email phone address citystate);
101     @item_fields     = qw(itemnumber barcode date_due);
102     @other_fields    = qw(type days_overdue fine);
103     $libname         = C4::Context->preference('LibraryName');
104     $control         = C4::Context->preference('CircControl');
105     $mode            = C4::Context->preference('finesMode');
106     $dbname          = C4::Context->config('database');
107     $delim           = "\t";                                                                          # ?  C4::Context->preference('delimiter') || "\t";
108
109 }
110
111 INIT {
112     $debug and print "Each line will contain the following fields:\n",
113       "From borrowers : ", join( ', ', @borrower_fields ), "\n",
114       "From items : ",     join( ', ', @item_fields ),     "\n",
115       "Per overdue: ",     join( ', ', @other_fields ),    "\n",
116       "Delimiter: '$delim'\n";
117 }
118 $debug and (defined $borrowernumberlimit) and print "--borrower limitation: borrower $borrowernumberlimit\n";
119 my ($numOverdueItems, $data);
120 if (defined $borrowernumberlimit) {
121     ($numOverdueItems, $data) = checkoverdues($borrowernumberlimit);
122 } else {
123     $data = Getoverdues();
124     $numOverdueItems = scalar @$data;
125 }
126 my $overdueItemsCounted = 0;
127 my %calendars           = ();
128 $today      = dt_from_string;
129 $today_iso  = output_pref( { dt => $today, dateonly => 1, dateformat => 'iso' } );
130 my ($tyear, $tmonth, $tday) = split( /-/, $today_iso );
131 $today_days = Date_to_Days( $tyear, $tmonth, $tday );
132
133 for ( my $i = 0 ; $i < scalar(@$data) ; $i++ ) {
134     next if $data->[$i]->{'itemlost'};
135     my ( $datedue, $datedue_days );
136     eval {
137         $datedue = dt_from_string( $data->[$i]->{'date_due'} );
138         my $datedue_iso = output_pref( { dt => $datedue, dateonly => 1, dateformat => 'iso' } );
139         $datedue_days = Date_to_Days( split( /-/, $datedue_iso ) );
140     };
141     if ($@) {
142     warn "Error on date for borrower " . $data->[$i]->{'borrowernumber'} .  ": $@date_due: " . $data->[$i]->{'date_due'} . "\ndatedue_days: " . $datedue_days . "\nSkipping";
143     next;
144     }
145     my $due_str = output_pref( { dt => $datedue, dateonly => 1 } );
146     unless ( defined $data->[$i]->{'borrowernumber'} ) {
147         print STDERR "ERROR in Getoverdues line $i: issues.borrowernumber IS NULL.  Repair 'issues' table now!  Skipping record.\n";
148         next;    # Note: this doesn't solve everything.  After NULL borrowernumber, multiple issues w/ real borrowernumbers can pile up.
149     }
150     my $patron = Koha::Patrons->find( $data->[$i]->{'borrowernumber'} );
151
152     # Skipping borrowers that are not in @categories
153     $bigdebug and warn "Skipping borrower from category " . $patron->categorycode if none { $patron->categorycode eq $_ } @categories;
154     next if none { $patron->categorycode eq $_ } @categories;
155
156     my $branchcode =
157         ( $useborrowerlibrary )           ? $patron->branchcode
158       : ( $control eq 'ItemHomeLibrary' ) ? $data->[$i]->{homebranch}
159       : ( $control eq 'PatronLibrary' )   ? $patron->branchcode
160       :                                     $data->[$i]->{branchcode};
161     # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here).
162
163     # Skipping branchcodes that are not in @libraries
164     $bigdebug and warn "Skipping library $branchcode" if none { $branchcode eq $_ } @libraries;
165     next if none { $branchcode eq $_ } @libraries;
166
167     my $calendar;
168     unless ( defined( $calendars{$branchcode} ) ) {
169         $calendars{$branchcode} = C4::Calendar->new( branchcode => $branchcode );
170     }
171     $calendar = $calendars{$branchcode};
172     my $isHoliday = $calendar->isHoliday( $tday, $tmonth, $tyear );
173
174     # Reassing datedue_days if -delay specified in commandline
175     $bigdebug and warn "Using commandline supplied delay : $delay" if ($delay);
176     $datedue_days += $delay if ($delay);
177
178     ( $datedue_days <= $today_days ) or next;    # or it's not overdue, right?
179
180     $overdueItemsCounted++;
181     my ( $amount, $unitcounttotal, $unitcount ) = CalcFine(
182         $data->[$i],
183         $patron->categorycode,
184         $branchcode,
185         $datedue,
186         $today,
187     );
188
189     # Reassign fine's amount if specified in command-line
190     $amount = $catamounts{$patron->categorycode} if (defined $catamounts{$patron->categorycode});
191
192     # We check if there is already a fine for the given borrower
193     my $fine = GetFine(undef, $data->[$i]->{'borrowernumber'});
194     if ($fine > 0) {
195         $debug and warn "There is already a fine for borrower " . $data->[$i]->{'borrowernumber'} . ". Nothing to do here. Skipping this borrower";
196         next;
197     }
198
199     # Don't update the fine if today is a holiday.
200     # This ensures that dropbox mode will remove the correct amount of fine.
201     if ( $mode eq 'production' and !$borrowersalreadyapplied->{$data->[$i]->{'borrowernumber'}}) {
202         # If we're on a holiday, warn the user (if debug) that no fine will be applied
203         if($isHoliday) {
204             $debug and warn "Today is a holiday. The fine for borrower " . $data->[$i]->{'borrowernumber'} . " will not be applied";
205         } else {
206             $debug and warn "Creating fine for borrower " . $data->[$i]->{'borrowernumber'} . " with amount : $amount";
207
208             # We mark this borrower as already processed
209             $borrowersalreadyapplied->{$data->[$i]->{'borrowernumber'}} = 1;
210
211             my $borrowernumber = $data->[$i]->{'borrowernumber'};
212             my $itemnumber     = $data->[$i]->{'itemnumber'};
213
214             # And we create the fine
215             my $sth4 = $dbh->prepare( "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?" );
216             $sth4->execute($itemnumber);
217             my $title = $sth4->fetchrow;
218
219             my $desc        = "staticfine";
220             my $query       = "INSERT INTO accountlines
221                         (borrowernumber,itemnumber,date,amount,description,debit_type_code,status,amountoutstanding)
222                                 VALUES (?,?,now(),?,?,'OVERDUE','RETURNED',?)";
223             my $sth2 = $dbh->prepare($query);
224             $bigdebug and warn "query: $query\nw/ args: $borrowernumber, $itemnumber, $amount, $desc, $amount\n";
225             $sth2->execute( $borrowernumber, $itemnumber, $amount, $desc, $amount );
226
227         }
228     }
229 }
230
231 if ($verbose) {
232     print <<EOM;
233 Fines assessment -- $today_iso
234 Number of Overdue Items:
235      counted $overdueItemsCounted
236     reported $numOverdueItems
237
238 EOM
239 }
240