Bug 34583: Overdue notice - wrong coding in outlook in czech e-mail in “print” mode
[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 my $verify_issue;
52
53 my $command_line_options = join(" ",@ARGV);
54
55 GetOptions(
56     'h|help'    => \$help,
57     'v|verbose' => \$verbose,
58     'l|log'     => \$log,
59     'o|out:s'   => \$output_dir,
60     'm|maxdays:i' => \$maxdays,
61     'i|verifyissue' => \$verify_issue,
62 );
63 my $usage = << 'ENDUSAGE';
64
65 This script calculates and charges overdue fines
66 to patron accounts.  The Koha system preference 'finesMode' controls
67 whether the fines are calculated and charged to the patron accounts ("Calculate and charge");
68 or not calculated ("Don't calculate").
69
70 This script has the following parameters :
71     -h --help: this message
72     -l --log: log the output to a file (optional if the -o parameter is given)
73     -o --out:  ouput directory for logs (defaults to env or /tmp if !exist)
74     -v --verbose
75     -m --maxdays: how many days back of overdues to process
76     -i --verifyissue: verify the issue before updating the fine in case the
77                item is returned while the fines job is running
78
79 ENDUSAGE
80
81 if ($help) {
82     print $usage;
83     exit;
84 }
85
86 my $script_handler = Koha::Script->new({ script => $0 });
87
88 try {
89     $script_handler->lock_exec;
90 }
91 catch {
92     my $message = "Skipping execution of $0 ($_)";
93     print STDERR "$message\n"
94         if $verbose;
95     cronlogaction({ info => $message });
96     exit;
97 };
98
99 cronlogaction({ info => $command_line_options });
100
101 my @borrower_fields =
102   qw(cardnumber categorycode surname firstname email phone address citystate);
103 my @item_fields  = qw(itemnumber barcode date_due);
104 my @other_fields = qw(days_overdue fine);
105 my $libname      = C4::Context->preference('LibraryName');
106 my $control      = C4::Context->preference('CircControl');
107 my $branch_type  = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
108 my $mode         = C4::Context->preference('finesMode');
109 my $delim = "\t";    # ?  C4::Context->preference('CSVDelimiter') || "\t";
110
111 my %is_holiday;
112 my $today = dt_from_string();
113 my $filename;
114 if ($log or $output_dir) {
115     $filename = get_filename($output_dir);
116 }
117
118 my $fh;
119 if ($filename) {
120     open $fh, '>>', $filename or croak "Cannot write file $filename: $!";
121     print {$fh} join $delim, ( @borrower_fields, @item_fields, @other_fields );
122     print {$fh} "\n";
123 }
124 my $counted = 0;
125 my $updated = 0;
126 my $params;
127 $params->{maximumdays} = $maxdays if $maxdays;
128 my $overdues = Getoverdues($params);
129 for my $overdue ( @{$overdues} ) {
130     next if $overdue->{itemlost};
131
132     if ( !defined $overdue->{borrowernumber} ) {
133         carp
134 "ERROR in Getoverdues : issues.borrowernumber IS NULL.  Repair 'issues' table now!  Skipping record.\n";
135         next;
136     }
137     my $patron = Koha::Patrons->find( $overdue->{borrowernumber} );
138     my $branchcode =
139         ( $control eq 'ItemHomeLibrary' ) ? $overdue->{$branch_type}
140       : ( $control eq 'PatronLibrary' )   ? $patron->branchcode
141       :                                     $overdue->{branchcode};
142
143 # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here).
144     if ( !exists $is_holiday{$branchcode} ) {
145         $is_holiday{$branchcode} = set_holiday( $branchcode, $today );
146     }
147
148     my $datedue = dt_from_string( $overdue->{date_due} );
149     if ( DateTime->compare( $datedue, $today ) == 1 ) {
150         next;    # not overdue
151     }
152     ++$counted;
153
154     my ( $amount, $unitcounttotal, $unitcount ) =
155       CalcFine( $overdue, $patron->categorycode,
156         $branchcode, $datedue, $today );
157
158     # Don't update the fine if today is a holiday.
159     # This ensures that dropbox mode will remove the correct amount of fine.
160     if (
161         $mode eq 'production'
162         && ( !$is_holiday{$branchcode}
163             || C4::Context->preference('ChargeFinesOnClosedDays') )
164         && ( $amount && $amount > 0 )
165       )
166     {
167         if ( $verify_issue ) {
168             # if the issue changed before the script got to it, then pass on it.
169             my $issue = Koha::Checkouts->find({ issue_id => $overdue->{issue_id} });
170             if ( ! $issue or $issue->date_due ne $overdue->{date_due} ) {
171                 $counted--;
172                 next;
173             }
174         }
175         UpdateFine(
176             {
177                 issue_id       => $overdue->{issue_id},
178                 itemnumber     => $overdue->{itemnumber},
179                 borrowernumber => $overdue->{borrowernumber},
180                 amount         => $amount,
181                 due            => $datedue,
182             }
183         );
184         $updated++;
185     }
186     my $borrower = $patron->unblessed;
187     if ($filename) {
188         my @cells;
189         push @cells,
190           map { defined $borrower->{$_} ? $borrower->{$_} : q{} }
191           @borrower_fields;
192         push @cells, map { $overdue->{$_} } @item_fields;
193         push @cells, $unitcounttotal, $amount;
194         say {$fh} join $delim, @cells;
195     }
196 }
197 if ($filename){
198     close $fh;
199 }
200
201 if ($verbose) {
202     my $overdue_items = @{$overdues};
203     print <<"EOM";
204 Fines assessment -- $today
205 EOM
206     if ($filename) {
207         say "Saved to $filename";
208     }
209     print <<"EOM";
210 Number of Overdue Items:
211      counted $overdue_items
212     reported $counted
213      updated $updated
214
215 EOM
216 }
217
218 cronlogaction({ action => 'End', info => "COMPLETED" });
219
220 sub set_holiday {
221     my ( $branch, $dt ) = @_;
222
223     my $calendar = Koha::Calendar->new( branchcode => $branch );
224     return $calendar->is_holiday($dt);
225 }
226
227 sub get_filename {
228     my $directory = shift;
229     if ( !$directory ) {
230         $directory = C4::Context::temporary_directory;
231     }
232     if ( !-d $directory ) {
233         carp "Could not write to $directory ... does not exist!";
234     }
235     my $name = C4::Context->config('database');
236     $name =~ s/\W//;
237     $name .= join q{}, q{_}, $today->ymd(), '.log';
238     $name = File::Spec->catfile( $directory, $name );
239     if ($verbose && $log) {
240         say "writing to $name";
241     }
242     return $name;
243 }