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