Bug 24651: Add maxdays option to fines cronjob
[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;
36 use Getopt::Long;
37 use Carp;
38 use File::Spec;
39
40 use Koha::Calendar;
41 use Koha::DateUtils;
42 use C4::Log;
43
44 my $help;
45 my $verbose;
46 my $output_dir;
47 my $log;
48 my $maxdays;
49
50 GetOptions(
51     'h|help'    => \$help,
52     'v|verbose' => \$verbose,
53     'l|log'     => \$log,
54     'o|out:s'   => \$output_dir,
55     'm|maxdays:i' => \$maxdays,
56 );
57 my $usage = << 'ENDUSAGE';
58
59 This script calculates and charges overdue fines
60 to patron accounts.  The Koha system preference 'finesMode' controls
61 whether the fines are calculated and charged to the patron accounts ("Calculate and charge");
62 calculated and emailed to the admin but not applied ("Calculate (but only for mailing to the admin)"); or not calculated ("Don't calculate").
63
64 This script has the following parameters :
65     -h --help: this message
66     -l --log: log the output to a file (optional if the -o parameter is given)
67     -o --out:  ouput directory for logs (defaults to env or /tmp if !exist)
68     -v --verbose
69     -m --maxdays: how many days back of overdues to process
70
71 ENDUSAGE
72
73 if ($help) {
74     print $usage;
75     exit;
76 }
77
78 cronlogaction();
79
80 my @borrower_fields =
81   qw(cardnumber categorycode surname firstname email phone address citystate);
82 my @item_fields  = qw(itemnumber barcode date_due);
83 my @other_fields = qw(days_overdue fine);
84 my $libname      = C4::Context->preference('LibraryName');
85 my $control      = C4::Context->preference('CircControl');
86 my $mode         = C4::Context->preference('finesMode');
87 my $delim = "\t";    # ?  C4::Context->preference('delimiter') || "\t";
88
89 my %is_holiday;
90 my $today = DateTime->now( time_zone => C4::Context->tz() );
91 my $filename;
92 if ($log or $output_dir) {
93     $filename = get_filename($output_dir);
94 }
95
96 my $fh;
97 if ($filename) {
98     open $fh, '>>', $filename or croak "Cannot write file $filename: $!";
99     print {$fh} join $delim, ( @borrower_fields, @item_fields, @other_fields );
100     print {$fh} "\n";
101 }
102 my $counted = 0;
103 my $params;
104 $params->{maximumdays} = $maxdays if $maxdays;
105 my $overdues = Getoverdues($params);
106 for my $overdue ( @{$overdues} ) {
107     next if $overdue->{itemlost};
108
109     if ( !defined $overdue->{borrowernumber} ) {
110         carp
111 "ERROR in Getoverdues : issues.borrowernumber IS NULL.  Repair 'issues' table now!  Skipping record.\n";
112         next;
113     }
114     my $borrower = BorType( $overdue->{borrowernumber} );
115     my $branchcode =
116         ( $control eq 'ItemHomeLibrary' ) ? $overdue->{homebranch}
117       : ( $control eq 'PatronLibrary' )   ? $borrower->{branchcode}
118       :                                     $overdue->{branchcode};
119
120 # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here).
121     if ( !exists $is_holiday{$branchcode} ) {
122         $is_holiday{$branchcode} = set_holiday( $branchcode, $today );
123     }
124
125     my $datedue = dt_from_string( $overdue->{date_due} );
126     if ( DateTime->compare( $datedue, $today ) == 1 ) {
127         next;    # not overdue
128     }
129     ++$counted;
130
131     my ( $amount, $unitcounttotal, $unitcount ) =
132       CalcFine( $overdue, $borrower->{categorycode},
133         $branchcode, $datedue, $today );
134
135     # Don't update the fine if today is a holiday.
136     # This ensures that dropbox mode will remove the correct amount of fine.
137     if ( $mode eq 'production' && !$is_holiday{$branchcode} ) {
138         if ( $amount && $amount > 0 ) {
139             UpdateFine(
140                 {
141                     issue_id       => $overdue->{issue_id},
142                     itemnumber     => $overdue->{itemnumber},
143                     borrowernumber => $overdue->{borrowernumber},
144                     amount         => $amount,
145                     due            => output_pref($datedue),
146                 }
147             );
148         }
149     }
150     if ($filename) {
151         my @cells;
152         push @cells,
153           map { defined $borrower->{$_} ? $borrower->{$_} : q{} }
154           @borrower_fields;
155         push @cells, map { $overdue->{$_} } @item_fields;
156         push @cells, $unitcounttotal, $amount;
157         say {$fh} join $delim, @cells;
158     }
159 }
160 if ($filename){
161     close $fh;
162 }
163
164 if ($verbose) {
165     my $overdue_items = @{$overdues};
166     print <<"EOM";
167 Fines assessment -- $today
168 EOM
169     if ($filename) {
170         say "Saved to $filename";
171     }
172     print <<"EOM";
173 Number of Overdue Items:
174      counted $overdue_items
175     reported $counted
176
177 EOM
178 }
179
180 sub set_holiday {
181     my ( $branch, $dt ) = @_;
182
183     my $calendar = Koha::Calendar->new( branchcode => $branch );
184     return $calendar->is_holiday($dt);
185 }
186
187 sub get_filename {
188     my $directory = shift;
189     if ( !$directory ) {
190         $directory = C4::Context::temporary_directory;
191     }
192     if ( !-d $directory ) {
193         carp "Could not write to $directory ... does not exist!";
194     }
195     my $name = C4::Context->config('database');
196     $name =~ s/\W//;
197     $name .= join q{}, q{_}, $today->ymd(), '.log';
198     $name = File::Spec->catfile( $directory, $name );
199     if ($verbose && $log) {
200         say "writing to $name";
201     }
202     return $name;
203 }