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