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