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