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