Bug 27259: Add HomeOrHoldingBranch checks where it was missing from
[koha.git] / misc / cronjobs / fines.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 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 2000-2002 Katipo Communications
12 # Copyright 2011 PTFS-Europe Ltd
13 #
14 # This file is part of Koha.
15 #
16 # Koha is free software; you can redistribute it and/or modify it
17 # under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 3 of the License, or
19 # (at your option) any later version.
20 #
21 # Koha is distributed in the hope that it will be useful, but
22 # WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 #
26 # You should have received a copy of the GNU General Public License
27 # along with Koha; if not, see <http://www.gnu.org/licenses>.
28
29 use strict;
30 use warnings;
31 use 5.010;
32
33 use Koha::Script -cron;
34 use C4::Context;
35 use C4::Overdues qw( Getoverdues CalcFine UpdateFine );
36 use Getopt::Long qw( GetOptions );
37 use Carp qw( carp croak );
38 use File::Spec;
39 use Try::Tiny qw( catch try );
40
41 use Koha::Calendar;
42 use Koha::DateUtils qw( dt_from_string output_pref );
43 use Koha::Patrons;
44 use C4::Log qw( cronlogaction );
45
46 my $help;
47 my $verbose;
48 my $output_dir;
49 my $log;
50 my $maxdays;
51
52 my $command_line_options = join(" ",@ARGV);
53
54 GetOptions(
55     'h|help'    => \$help,
56     'v|verbose' => \$verbose,
57     'l|log'     => \$log,
58     'o|out:s'   => \$output_dir,
59     'm|maxdays:i' => \$maxdays,
60 );
61 my $usage = << 'ENDUSAGE';
62
63 This script calculates and charges overdue fines
64 to patron accounts.  The Koha system preference 'finesMode' controls
65 whether the fines are calculated and charged to the patron accounts ("Calculate and charge");
66 or not calculated ("Don't calculate").
67
68 This script has the following parameters :
69     -h --help: this message
70     -l --log: log the output to a file (optional if the -o parameter is given)
71     -o --out:  ouput directory for logs (defaults to env or /tmp if !exist)
72     -v --verbose
73     -m --maxdays: how many days back of overdues to process
74
75 ENDUSAGE
76
77 if ($help) {
78     print $usage;
79     exit;
80 }
81
82 my $script_handler = Koha::Script->new({ script => $0 });
83
84 try {
85     $script_handler->lock_exec;
86 }
87 catch {
88     my $message = "Skipping execution of $0 ($_)";
89     print STDERR "$message\n"
90         if $verbose;
91     cronlogaction( $message );
92     exit;
93 };
94
95 cronlogaction({ info => $command_line_options });
96
97 my @borrower_fields =
98   qw(cardnumber categorycode surname firstname email phone address citystate);
99 my @item_fields  = qw(itemnumber barcode date_due);
100 my @other_fields = qw(days_overdue fine);
101 my $libname      = C4::Context->preference('LibraryName');
102 my $control      = C4::Context->preference('CircControl');
103 my $branch_type  = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
104 my $mode         = C4::Context->preference('finesMode');
105 my $delim = "\t";    # ?  C4::Context->preference('CSVDelimiter') || "\t";
106
107 my %is_holiday;
108 my $today = dt_from_string();
109 my $filename;
110 if ($log or $output_dir) {
111     $filename = get_filename($output_dir);
112 }
113
114 my $fh;
115 if ($filename) {
116     open $fh, '>>', $filename or croak "Cannot write file $filename: $!";
117     print {$fh} join $delim, ( @borrower_fields, @item_fields, @other_fields );
118     print {$fh} "\n";
119 }
120 my $counted = 0;
121 my $updated = 0;
122 my $params;
123 $params->{maximumdays} = $maxdays if $maxdays;
124 my $overdues = Getoverdues($params);
125 for my $overdue ( @{$overdues} ) {
126     next if $overdue->{itemlost};
127
128     if ( !defined $overdue->{borrowernumber} ) {
129         carp
130 "ERROR in Getoverdues : issues.borrowernumber IS NULL.  Repair 'issues' table now!  Skipping record.\n";
131         next;
132     }
133     my $patron = Koha::Patrons->find( $overdue->{borrowernumber} );
134     my $branchcode =
135         ( $control eq 'ItemHomeLibrary' ) ? $overdue->{$branch_type}
136       : ( $control eq 'PatronLibrary' )   ? $patron->branchcode
137       :                                     $overdue->{branchcode};
138
139 # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here).
140     if ( !exists $is_holiday{$branchcode} ) {
141         $is_holiday{$branchcode} = set_holiday( $branchcode, $today );
142     }
143
144     my $datedue = dt_from_string( $overdue->{date_due} );
145     if ( DateTime->compare( $datedue, $today ) == 1 ) {
146         next;    # not overdue
147     }
148     ++$counted;
149
150     my ( $amount, $unitcounttotal, $unitcount ) =
151       CalcFine( $overdue, $patron->categorycode,
152         $branchcode, $datedue, $today );
153
154     # Don't update the fine if today is a holiday.
155     # This ensures that dropbox mode will remove the correct amount of fine.
156     if (
157         $mode eq 'production'
158         && ( !$is_holiday{$branchcode}
159             || C4::Context->preference('ChargeFinesOnClosedDays') )
160         && ( $amount && $amount > 0 )
161       )
162     {
163         UpdateFine(
164             {
165                 issue_id       => $overdue->{issue_id},
166                 itemnumber     => $overdue->{itemnumber},
167                 borrowernumber => $overdue->{borrowernumber},
168                 amount         => $amount,
169                 due            => $datedue,
170             }
171         );
172         $updated++;
173     }
174     my $borrower = $patron->unblessed;
175     if ($filename) {
176         my @cells;
177         push @cells,
178           map { defined $borrower->{$_} ? $borrower->{$_} : q{} }
179           @borrower_fields;
180         push @cells, map { $overdue->{$_} } @item_fields;
181         push @cells, $unitcounttotal, $amount;
182         say {$fh} join $delim, @cells;
183     }
184 }
185 if ($filename){
186     close $fh;
187 }
188
189 if ($verbose) {
190     my $overdue_items = @{$overdues};
191     print <<"EOM";
192 Fines assessment -- $today
193 EOM
194     if ($filename) {
195         say "Saved to $filename";
196     }
197     print <<"EOM";
198 Number of Overdue Items:
199      counted $overdue_items
200     reported $counted
201      updated $updated
202
203 EOM
204 }
205
206 cronlogaction({ action => 'End', info => "COMPLETED" });
207
208 sub set_holiday {
209     my ( $branch, $dt ) = @_;
210
211     my $calendar = Koha::Calendar->new( branchcode => $branch );
212     return $calendar->is_holiday($dt);
213 }
214
215 sub get_filename {
216     my $directory = shift;
217     if ( !$directory ) {
218         $directory = C4::Context::temporary_directory;
219     }
220     if ( !-d $directory ) {
221         carp "Could not write to $directory ... does not exist!";
222     }
223     my $name = C4::Context->config('database');
224     $name =~ s/\W//;
225     $name .= join q{}, q{_}, $today->ymd(), '.log';
226     $name = File::Spec->catfile( $directory, $name );
227     if ($verbose && $log) {
228         say "writing to $name";
229     }
230     return $name;
231 }