Bug 2505 - Add commented use warnings where missing in *.pm
[koha.git] / C4 / Overdues.pm
1 package C4::Overdues;
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use Date::Calc qw/Today Date_to_Days/;
24 use Date::Manip qw/UnixDate/;
25 use C4::Circulation;
26 use C4::Context;
27 use C4::Accounts;
28 use C4::Log; # logaction
29 use C4::Debug;
30
31 use vars qw($VERSION @ISA @EXPORT);
32
33 BEGIN {
34         # set the version for version checking
35         $VERSION = 3.01;
36         require Exporter;
37         @ISA    = qw(Exporter);
38         # subs to rename (and maybe merge some...)
39         push @EXPORT, qw(
40         &CalcFine
41         &Getoverdues
42         &checkoverdues
43         &CheckAccountLineLevelInfo
44         &CheckAccountLineItemInfo
45         &CheckExistantNotifyid
46         &GetNextIdNotify
47         &GetNotifyId
48         &NumberNotifyId
49         &AmountNotify
50         &UpdateAccountLines
51         &UpdateFine
52         &GetOverdueDelays
53         &GetOverduerules
54         &GetFine
55         &CreateItemAccountLine
56         &ReplacementCost2
57         
58         &CheckItemNotify
59         &GetOverduesForBranch
60         &RemoveNotifyLine
61         &AddNotifyLine
62         );
63         # subs to remove
64         push @EXPORT, qw(
65         &BorType
66         );
67
68         # check that an equivalent don't exist already before moving
69
70         # subs to move to Circulation.pm
71         push @EXPORT, qw(
72         &GetIssuesIteminfo
73         );
74     #
75         # &GetIssuingRules - delete.
76         # use C4::Circulation::GetIssuingRule instead.
77         
78         # subs to move to Members.pm
79         push @EXPORT, qw(
80         &CheckBorrowerDebarred
81         &UpdateBorrowerDebarred
82         );
83         # subs to move to Biblio.pm
84         push @EXPORT, qw(
85         &GetItems
86         &ReplacementCost
87         );
88 }
89
90 =head1 NAME
91
92 C4::Circulation::Fines - Koha module dealing with fines
93
94 =head1 SYNOPSIS
95
96   use C4::Overdues;
97
98 =head1 DESCRIPTION
99
100 This module contains several functions for dealing with fines for
101 overdue items. It is primarily used by the 'misc/fines2.pl' script.
102
103 =head1 FUNCTIONS
104
105 =head2 Getoverdues
106
107   $overdues = Getoverdues( { minimumdays => 1, maximumdays => 30 } );
108
109 Returns the list of all overdue books, with their itemtype.
110
111 C<$overdues> is a reference-to-array. Each element is a
112 reference-to-hash whose keys are the fields of the issues table in the
113 Koha database.
114
115 =cut
116
117 #'
118 sub Getoverdues {
119     my $params = shift;
120     my $dbh = C4::Context->dbh;
121     my $statement;
122     if ( C4::Context->preference('item-level_itypes') ) {
123         $statement = "
124    SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode
125      FROM issues 
126 LEFT JOIN items       USING (itemnumber)
127     WHERE date_due < CURDATE() 
128 ";
129     } else {
130         $statement = "
131    SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode
132      FROM issues 
133 LEFT JOIN items       USING (itemnumber)
134 LEFT JOIN biblioitems USING (biblioitemnumber)
135     WHERE date_due < CURDATE() 
136 ";
137     }
138
139     my @bind_parameters;
140     if ( exists $params->{'minimumdays'} and exists $params->{'maximumdays'} ) {
141         $statement .= ' AND TO_DAYS( NOW() )-TO_DAYS( date_due ) BETWEEN ? and ? ';
142         push @bind_parameters, $params->{'minimumdays'}, $params->{'maximumdays'};
143     } elsif ( exists $params->{'minimumdays'} ) {
144         $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) > ? ';
145         push @bind_parameters, $params->{'minimumdays'};
146     } elsif ( exists $params->{'maximumdays'} ) {
147         $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ? ';
148         push @bind_parameters, $params->{'maximumdays'};
149     }
150     $statement .= 'ORDER BY borrowernumber';
151     my $sth = $dbh->prepare( $statement );
152     $sth->execute( @bind_parameters );
153     return $sth->fetchall_arrayref({});
154 }
155
156
157 =head2 checkoverdues
158
159 ($count, $overdueitems) = checkoverdues($borrowernumber);
160
161 Returns a count and a list of overdueitems for a given borrowernumber
162
163 =cut
164
165 sub checkoverdues {
166     my $borrowernumber = shift or return;
167     my $sth = C4::Context->dbh->prepare(
168         "SELECT * FROM issues
169          LEFT JOIN items       ON issues.itemnumber      = items.itemnumber
170          LEFT JOIN biblio      ON items.biblionumber     = biblio.biblionumber
171          LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
172             WHERE issues.borrowernumber  = ?
173             AND   issues.date_due < CURDATE()"
174     );
175     # FIXME: SELECT * across 4 tables?  do we really need the marc AND marcxml blobs??
176     $sth->execute($borrowernumber);
177     my $results = $sth->fetchall_arrayref({});
178     return ( scalar(@$results), $results);  # returning the count and the results is silly
179 }
180
181 =head2 CalcFine
182
183   ($amount, $chargename, $daycount, $daycounttotal) =
184     &CalcFine($item, $categorycode, $branch, $days_overdue, $description, $start_date, $end_date );
185
186 Calculates the fine for a book.
187
188 The issuingrules table in the Koha database is a fine matrix, listing
189 the penalties for each type of patron for each type of item and each branch (e.g., the
190 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
191 members might get a longer grace period between the first and second
192 reminders that a book is overdue).
193
194
195 C<$item> is an item object (hashref).
196
197 C<$categorycode> is the category code (string) of the patron who currently has
198 the book.
199
200 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
201
202 C<$days_overdue> is the number of days elapsed since the book's due date.
203   NOTE: supplying days_overdue is deprecated.
204
205 C<$start_date> & C<$end_date> are C4::Dates objects 
206 defining the date range over which to determine the fine.
207 Note that if these are defined, we ignore C<$difference> and C<$dues> , 
208 but retain these for backwards-comptibility with extant fines scripts.
209
210 Fines scripts should just supply the date range over which to calculate the fine.
211
212 C<&CalcFine> returns four values:
213
214 C<$amount> is the fine owed by the patron (see above).
215
216 C<$chargename> is the chargename field from the applicable record in
217 the categoryitem table, whatever that is.
218
219 C<$daycount> is the number of days between start and end dates, Calendar adjusted (where needed), 
220 minus any applicable grace period.
221
222 C<$daycounttotal> is C<$daycount> without consideration of grace period.
223
224 FIXME - What is chargename supposed to be ?
225
226 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
227 or "Final Notice".  But CalcFine never defined any value.
228
229 =cut
230
231 sub CalcFine {
232     my ( $item, $bortype, $branchcode, $difference ,$dues , $start_date, $end_date  ) = @_;
233         $debug and warn sprintf("CalcFine(%s, %s, %s, %s, %s, %s, %s)",
234                         ($item ? '{item}' : 'UNDEF'), 
235                         ($bortype    || 'UNDEF'), 
236                         ($branchcode || 'UNDEF'), 
237                         ($difference || 'UNDEF'), 
238                         ($dues       || 'UNDEF'), 
239                         ($start_date ? ($start_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF'), 
240                         (  $end_date ? (  $end_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF')
241         );
242     my $dbh = C4::Context->dbh;
243     my $amount = 0;
244         my $daystocharge;
245         # get issuingrules (fines part will be used)
246     $debug and warn sprintf("CalcFine calling GetIssuingRule(%s, %s, %s)", $bortype, $item->{'itemtype'}, $branchcode);
247     my $data = C4::Circulation::GetIssuingRule($bortype, $item->{'itemtype'}, $branchcode);
248         if($difference) {
249                 # if $difference is supplied, the difference has already been calculated, but we still need to adjust for the calendar.
250         # use copy-pasted functions from calendar module.  (deprecated -- these functions will be removed from C4::Overdues ).
251             my $countspecialday    =    &GetSpecialHolidays($dues,$item->{itemnumber});
252             my $countrepeatableday = &GetRepeatableHolidays($dues,$item->{itemnumber},$difference);    
253             my $countalldayclosed  = $countspecialday + $countrepeatableday;
254             $daystocharge = $difference - $countalldayclosed;
255         } else {
256                 # if $difference is not supplied, we have C4::Dates objects giving us the date range, and we use the calendar module.
257                 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
258                         my $calendar = C4::Calendar->new( branchcode => $branchcode );
259                         $daystocharge = $calendar->daysBetween( $start_date, $end_date );
260                 } else {
261                         $daystocharge = Date_to_Days(split('-',$end_date->output('iso'))) - Date_to_Days(split('-',$start_date->output('iso')));
262                 }
263         }
264         # correct for grace period.
265         my $days_minus_grace = $daystocharge - $data->{'firstremind'};
266     if ($data->{'chargeperiod'} > 0 && $days_minus_grace > 0 ) { 
267         $amount = int($daystocharge / $data->{'chargeperiod'}) * $data->{'fine'};
268     } else {
269         # a zero (or null)  chargeperiod means no charge.
270     }
271         $amount = C4::Context->preference('maxFine') if(C4::Context->preference('maxFine') && ( $amount > C4::Context->preference('maxFine')));
272         $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
273     return ($amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
274     # FIXME: chargename is NEVER populated anywhere.
275 }
276
277
278 =head2 GetSpecialHolidays
279
280 &GetSpecialHolidays($date_dues,$itemnumber);
281
282 return number of special days  between date of the day and date due
283
284 C<$date_dues> is the envisaged date of book return.
285
286 C<$itemnumber> is the book's item number.
287
288 =cut
289
290 sub GetSpecialHolidays {
291     my ( $date_dues, $itemnumber ) = @_;
292
293     # calcul the today date
294     my $today = join "-", &Today();
295
296     # return the holdingbranch
297     my $iteminfo = GetIssuesIteminfo($itemnumber);
298
299     # use sql request to find all date between date_due and today
300     my $dbh = C4::Context->dbh;
301     my $query =
302       qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
303 FROM `special_holidays`
304 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
305 AND   DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
306 AND branchcode=?
307 |;
308     my @result = GetWdayFromItemnumber($itemnumber);
309     my @result_date;
310     my $wday;
311     my $dateinsec;
312     my $sth = $dbh->prepare($query);
313     $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
314       ;    # FIXME: just use NOW() in SQL instead of passing in $today
315
316     while ( my $special_date = $sth->fetchrow_hashref ) {
317         push( @result_date, $special_date );
318     }
319
320     my $specialdaycount = scalar(@result_date);
321
322     for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
323         $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
324         ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
325           localtime($dateinsec);
326         for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
327             if ( $wday == ( $result[$j]->{'weekday'} ) ) {
328                 $specialdaycount--;
329             }
330         }
331     }
332
333     return $specialdaycount;
334 }
335
336 =head2 GetRepeatableHolidays
337
338 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
339
340 return number of day closed between date of the day and date due
341
342 C<$date_dues> is the envisaged date of book return.
343
344 C<$itemnumber> is item number.
345
346 C<$difference> numbers of between day date of the day and date due
347
348 =cut
349
350 sub GetRepeatableHolidays {
351     my ( $date_dues, $itemnumber, $difference ) = @_;
352     my $dateinsec = UnixDate( $date_dues, "%o" );
353     my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
354       localtime($dateinsec);
355     my @result = GetWdayFromItemnumber($itemnumber);
356     my @dayclosedcount;
357     my $j;
358
359     for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
360         my $k = $wday;
361
362         for ( $j = 0 ; $j < $difference ; $j++ ) {
363             if ( $result[$i]->{'weekday'} == $k ) {
364                 push( @dayclosedcount, $k );
365             }
366             $k++;
367             ( $k = 0 ) if ( $k eq 7 );
368         }
369     }
370     return scalar(@dayclosedcount);
371 }
372
373
374 =head2 GetWayFromItemnumber
375
376 &Getwdayfromitemnumber($itemnumber);
377
378 return the different week day from repeatable_holidays table
379
380 C<$itemnumber> is  item number.
381
382 =cut
383
384 sub GetWdayFromItemnumber {
385     my ($itemnumber) = @_;
386     my $iteminfo = GetIssuesIteminfo($itemnumber);
387     my @result;
388     my $query = qq|SELECT weekday
389     FROM repeatable_holidays
390     WHERE branchcode=?
391 |;
392     my $sth = C4::Context->dbh->prepare($query);
393
394     $sth->execute( $iteminfo->{'branchcode'} );
395     while ( my $weekday = $sth->fetchrow_hashref ) {
396         push( @result, $weekday );
397     }
398     return @result;
399 }
400
401
402 =head2 GetIssuesIteminfo
403
404 &GetIssuesIteminfo($itemnumber);
405
406 return all data from issues about item
407
408 C<$itemnumber> is  item number.
409
410 =cut
411
412 sub GetIssuesIteminfo {
413     my ($itemnumber) = @_;
414     my $dbh          = C4::Context->dbh;
415     my $query        = qq|SELECT *
416     FROM issues
417     WHERE itemnumber=?
418     |;
419     my $sth = $dbh->prepare($query);
420     $sth->execute($itemnumber);
421     my ($issuesinfo) = $sth->fetchrow_hashref;
422     return $issuesinfo;
423 }
424
425
426 =head2 UpdateFine
427
428   &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
429
430 (Note: the following is mostly conjecture and guesswork.)
431
432 Updates the fine owed on an overdue book.
433
434 C<$itemnumber> is the book's item number.
435
436 C<$borrowernumber> is the borrower number of the patron who currently
437 has the book on loan.
438
439 C<$amount> is the current amount owed by the patron.
440
441 C<$type> will be used in the description of the fine.
442
443 C<$description> is a string that must be present in the description of
444 the fine. I think this is expected to be a date in DD/MM/YYYY format.
445
446 C<&UpdateFine> looks up the amount currently owed on the given item
447 and sets it to C<$amount>, creating, if necessary, a new entry in the
448 accountlines table of the Koha database.
449
450 =cut
451
452 #
453 # Question: Why should the caller have to
454 # specify both the item number and the borrower number? A book can't
455 # be on loan to two different people, so the item number should be
456 # sufficient.
457 #
458 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
459 #
460 sub UpdateFine {
461     my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
462         $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
463     my $dbh = C4::Context->dbh;
464     # FIXME - What exactly is this query supposed to do? It looks up an
465     # entry in accountlines that matches the given item and borrower
466     # numbers, where the description contains $due, and where the
467     # account type has one of several values, but what does this _mean_?
468     # Does it look up existing fines for this item?
469     # FIXME - What are these various account types? ("FU", "O", "F", "M")
470         #       "L"   is LOST item
471         #   "A"   is Account Management Fee
472         #   "N"   is New Card
473         #   "M"   is Sundry
474         #   "O"   is Overdue ??
475         #   "F"   is Fine ??
476         #   "FU"  is Fine UPDATE??
477         #       "Pay" is Payment
478         #   "REF" is Cash Refund
479     my $sth = $dbh->prepare(
480         "SELECT * FROM accountlines
481                 WHERE itemnumber=?
482                 AND   borrowernumber=?
483                 AND   accounttype IN ('FU','O','F','M')
484                 AND   description like ? "
485     );
486     $sth->execute( $itemnum, $borrowernumber, "%$due%" );
487
488     if ( my $data = $sth->fetchrow_hashref ) {
489
490                 # we're updating an existing fine.  Only modify if we're adding to the charge.
491         # Note that in the current implementation, you cannot pay against an accruing fine
492         # (i.e. , of accounttype 'FU').  Doing so will break accrual.
493         if ( $data->{'amount'} != $amount ) {
494             my $diff = $amount - $data->{'amount'};
495             $diff = 0 if ( $data->{amount} > $amount);
496             my $out  = $data->{'amountoutstanding'} + $diff;
497             my $query = "
498                 UPDATE accountlines
499                                 SET date=now(), amount=?, amountoutstanding=?,
500                                         lastincrement=?, accounttype='FU'
501                                 WHERE borrowernumber=?
502                                 AND   itemnumber=?
503                                 AND   accounttype IN ('FU','O')
504                                 AND   description LIKE ?
505                                 LIMIT 1 ";
506             my $sth2 = $dbh->prepare($query);
507                         # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
508                         #               LIMIT 1 added to prevent multiple affected lines
509                         # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.  
510                         #               But actually, we should just have a regular autoincrementing PK and forget accountline,
511                         #               including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
512                         # FIXME: Why only 2 account types here?
513                         $debug and print STDERR "UpdateFine query: $query\n" .
514                                 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
515             $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
516         } else {
517             #      print "no update needed $data->{'amount'}"
518         }
519     } else {
520         my $sth4 = $dbh->prepare(
521             "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
522         );
523         $sth4->execute($itemnum);
524         my $title = $sth4->fetchrow;
525
526 #         #   print "not in account";
527 #         my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
528 #         $sth3->execute;
529
530 #         # FIXME - Make $accountno a scalar.
531 #         my @accountno = $sth3->fetchrow_array;
532 #         $sth3->finish;
533 #         $accountno[0]++;
534 # begin transaction
535                 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
536                 my $desc = ($type ? "$type " : '') . "$title $due";     # FIXEDME, avoid whitespace prefix on empty $type
537                 my $query = "INSERT INTO accountlines
538                     (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
539                             VALUES (?,?,now(),?,?,'FU',?,?,?)";
540                 my $sth2 = $dbh->prepare($query);
541                 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
542         $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
543     }
544     # logging action
545     &logaction(
546         "FINES",
547         $type,
548         $borrowernumber,
549         "due=".$due."  amount=".$amount." itemnumber=".$itemnum
550         ) if C4::Context->preference("FinesLog");
551 }
552
553 =head2 BorType
554
555   $borrower = &BorType($borrowernumber);
556
557 Looks up a patron by borrower number.
558
559 C<$borrower> is a reference-to-hash whose keys are all of the fields
560 from the borrowers and categories tables of the Koha database. Thus,
561 C<$borrower> contains all information about both the borrower and
562 category he or she belongs to.
563
564 =cut
565
566 #'
567 sub BorType {
568     my ($borrowernumber) = @_;
569     my $dbh              = C4::Context->dbh;
570     my $sth              = $dbh->prepare(
571         "SELECT * from borrowers
572       LEFT JOIN categories ON borrowers.categorycode=categories.categorycode 
573       WHERE borrowernumber=?"
574     );
575     $sth->execute($borrowernumber);
576     return $sth->fetchrow_hashref;
577 }
578
579 =head2 ReplacementCost
580
581   $cost = &ReplacementCost($itemnumber);
582
583 Returns the replacement cost of the item with the given item number.
584
585 =cut
586
587 #'
588 sub ReplacementCost {
589     my ($itemnum) = @_;
590     my $dbh       = C4::Context->dbh;
591     my $sth       =
592       $dbh->prepare("Select replacementprice from items where itemnumber=?");
593     $sth->execute($itemnum);
594
595     # FIXME - Use fetchrow_array or a slice.
596     my $data = $sth->fetchrow_hashref;
597     return ( $data->{'replacementprice'} );
598 }
599
600 =head2 GetFine
601
602 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
603
604 return the total of fine
605
606 C<$itemnum> is item number
607
608 C<$borrowernumber> is the borrowernumber
609
610 =cut 
611
612
613 sub GetFine {
614     my ( $itemnum, $borrowernumber ) = @_;
615     my $dbh   = C4::Context->dbh();
616     my $query = "SELECT sum(amountoutstanding) FROM accountlines
617     where accounttype like 'F%'  
618   AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
619     my $sth = $dbh->prepare($query);
620     $sth->execute( $itemnum, $borrowernumber );
621     my $data = $sth->fetchrow_hashref();
622     return ( $data->{'sum(amountoutstanding)'} );
623 }
624
625
626 =head2 GetIssuingRules
627
628 FIXME - This sub should be deprecated and removed.
629 It ignores branch and defaults.
630
631 $data = &GetIssuingRules($itemtype,$categorycode);
632
633 Looks up for all issuingrules an item info 
634
635 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
636 from the borrowers and categories tables of the Koha database. Thus,
637
638 C<$categorycode> contains  information about borrowers category 
639
640 C<$data> contains all information about both the borrower and
641 category he or she belongs to.
642 =cut 
643
644 sub GetIssuingRules {
645         warn "GetIssuingRules is deprecated: use GetIssuingRule from C4::Circulation instead.";
646    my ($itemtype,$categorycode)=@_;
647    my $dbh   = C4::Context->dbh();    
648    my $query=qq|SELECT *
649         FROM issuingrules
650         WHERE issuingrules.itemtype=?
651             AND issuingrules.categorycode=?
652         |;
653     my $sth = $dbh->prepare($query);
654     #  print $query;
655     $sth->execute($itemtype,$categorycode);
656     return $sth->fetchrow_hashref;
657 }
658
659
660 sub ReplacementCost2 {
661     my ( $itemnum, $borrowernumber ) = @_;
662     my $dbh   = C4::Context->dbh();
663     my $query = "SELECT amountoutstanding
664          FROM accountlines
665              WHERE accounttype like 'L'
666          AND amountoutstanding > 0
667          AND itemnumber = ?
668          AND borrowernumber= ?";
669     my $sth = $dbh->prepare($query);
670     $sth->execute( $itemnum, $borrowernumber );
671     my $data = $sth->fetchrow_hashref();
672     return ( $data->{'amountoutstanding'} );
673 }
674
675
676 =head2 GetNextIdNotify
677
678 ($result) = &GetNextIdNotify($reference);
679
680 Returns the new file number
681
682 C<$result> contains the next file number
683
684 C<$reference> contains the beggining of file number
685
686 =cut
687
688 sub GetNextIdNotify {
689     my ($reference) = @_;
690     my $query = qq|SELECT max(notify_id)
691          FROM accountlines
692          WHERE notify_id  like \"$reference%\"
693          |;
694
695     # AND borrowernumber=?|;
696     my $dbh = C4::Context->dbh;
697     my $sth = $dbh->prepare($query);
698     $sth->execute();
699     my $result = $sth->fetchrow;
700     my $count;
701     if ( $result eq '' ) {
702         ( $result = $reference . "01" );
703     }
704     else {
705         $count = substr( $result, 6 ) + 1;
706
707         if ( $count < 10 ) {
708             ( $count = "0" . $count );
709         }
710         $result = $reference . $count;
711     }
712     return $result;
713 }
714
715 =head2 NumberNotifyId
716
717 (@notify) = &NumberNotifyId($borrowernumber);
718
719 Returns amount for all file per borrowers
720 C<@notify> array contains all file per borrowers
721
722 C<$notify_id> contains the file number for the borrower number nad item number
723
724 =cut
725
726 sub NumberNotifyId{
727     my ($borrowernumber)=@_;
728     my $dbh = C4::Context->dbh;
729     my $query=qq|    SELECT distinct(notify_id)
730             FROM accountlines
731             WHERE borrowernumber=?|;
732     my @notify;
733     my $sth = $dbh->prepare($query);
734     $sth->execute($borrowernumber);
735     while ( my ($numberofnotify) = $sth->fetchrow ) {
736         push( @notify, $numberofnotify );
737     }
738     return (@notify);
739 }
740
741 =head2 AmountNotify
742
743 ($totalnotify) = &AmountNotify($notifyid);
744
745 Returns amount for all file per borrowers
746 C<$notifyid> is the file number
747
748 C<$totalnotify> contains amount of a file
749
750 C<$notify_id> contains the file number for the borrower number and item number
751
752 =cut
753
754 sub AmountNotify{
755     my ($notifyid,$borrowernumber)=@_;
756     my $dbh = C4::Context->dbh;
757     my $query=qq|    SELECT sum(amountoutstanding)
758             FROM accountlines
759             WHERE notify_id=? AND borrowernumber = ?|;
760     my $sth=$dbh->prepare($query);
761         $sth->execute($notifyid,$borrowernumber);
762         my $totalnotify=$sth->fetchrow;
763     $sth->finish;
764     return ($totalnotify);
765 }
766
767
768 =head2 GetNotifyId
769
770 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
771
772 Returns the file number per borrower and itemnumber
773
774 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
775 from the items tables of the Koha database. Thus,
776
777 C<$itemnumber> contains the borrower categorycode
778
779 C<$notify_id> contains the file number for the borrower number nad item number
780
781 =cut
782
783 sub GetNotifyId {
784     my ( $borrowernumber, $itemnumber ) = @_;
785     my $query = qq|SELECT notify_id
786            FROM accountlines
787            WHERE borrowernumber=?
788           AND itemnumber=?
789            AND (accounttype='FU' or accounttype='O')|;
790     my $dbh = C4::Context->dbh;
791     my $sth = $dbh->prepare($query);
792     $sth->execute( $borrowernumber, $itemnumber );
793     my ($notify_id) = $sth->fetchrow;
794     $sth->finish;
795     return ($notify_id);
796 }
797
798 =head2 CreateItemAccountLine
799
800 () = &CreateItemAccountLine($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
801
802 update the account lines with file number or with file level
803
804 C<$items> is a reference-to-hash whose keys are all of the fields
805 from the items tables of the Koha database. Thus,
806
807 C<$itemnumber> contains the item number
808
809 C<$borrowernumber> contains the borrower number
810
811 C<$date> contains the date of the day
812
813 C<$amount> contains item price
814
815 C<$description> contains the descritpion of accounttype 
816
817 C<$accounttype> contains the account type
818
819 C<$amountoutstanding> contains the $amountoutstanding 
820
821 C<$timestamp> contains the timestamp with time and the date of the day
822
823 C<$notify_id> contains the file number
824
825 C<$level> contains the file level
826
827 =cut
828
829 sub CreateItemAccountLine {
830     my (
831         $borrowernumber, $itemnumber,  $date,              $amount,
832         $description,    $accounttype, $amountoutstanding, $timestamp,
833         $notify_id,      $level
834     ) = @_;
835     my $dbh         = C4::Context->dbh;
836     my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
837     my $query       = "INSERT into accountlines
838          (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
839           VALUES
840              (?,?,?,?,?,?,?,?,?,?,?)";
841
842     my $sth = $dbh->prepare($query);
843     $sth->execute(
844         $borrowernumber, $nextaccntno,       $itemnumber,
845         $date,           $amount,            $description,
846         $accounttype,    $amountoutstanding, $timestamp,
847         $notify_id,      $level
848     );
849 }
850
851 =head2 UpdateAccountLines
852
853 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
854
855 update the account lines with file number or with file level
856
857 C<$items> is a reference-to-hash whose keys are all of the fields
858 from the items tables of the Koha database. Thus,
859
860 C<$itemnumber> contains the item number
861
862 C<$notify_id> contains the file number
863
864 C<$notify_level> contains the file level
865
866 C<$borrowernumber> contains the borrowernumber
867
868 =cut
869
870 sub UpdateAccountLines {
871     my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
872     my $query;
873     if ( $notify_id eq '' ) {
874         $query = qq|UPDATE accountlines
875     SET  notify_level=?
876     WHERE borrowernumber=? AND itemnumber=?
877     AND (accounttype='FU' or accounttype='O')|;
878     } else {
879         $query = qq|UPDATE accountlines
880      SET notify_id=?, notify_level=?
881    WHERE borrowernumber=?
882     AND itemnumber=?
883     AND (accounttype='FU' or accounttype='O')|;
884     }
885
886     my $sth = C4::Context->dbh->prepare($query);
887     if ( $notify_id eq '' ) {
888         $sth->execute( $notify_level, $borrowernumber, $itemnumber );
889     } else {
890         $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
891     }
892 }
893
894 =head2 GetItems
895
896 ($items) = &GetItems($itemnumber);
897
898 Returns the list of all delays from overduerules.
899
900 C<$items> is a reference-to-hash whose keys are all of the fields
901 from the items tables of the Koha database. Thus,
902
903 C<$itemnumber> contains the borrower categorycode
904
905 =cut
906
907 # FIXME: This is a bad function to have here.
908 # Shouldn't it be in C4::Items?
909 # Shouldn't it be called GetItem since you only get 1 row?
910 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
911
912 sub GetItems {
913     my $itemnumber = shift or return;
914     my $query = qq|SELECT *
915              FROM items
916               WHERE itemnumber=?|;
917     my $sth = C4::Context->dbh->prepare($query);
918     $sth->execute($itemnumber);
919     my ($items) = $sth->fetchrow_hashref;
920     return ($items);
921 }
922
923 =head2 GetOverdueDelays
924
925 (@delays) = &GetOverdueDelays($categorycode);
926
927 Returns the list of all delays from overduerules.
928
929 C<@delays> it's an array contains the three delays from overduerules table
930
931 C<$categorycode> contains the borrower categorycode
932
933 =cut
934
935 sub GetOverdueDelays {
936     my ($category) = @_;
937     my $query      = qq|SELECT delay1,delay2,delay3
938                 FROM overduerules
939                 WHERE categorycode=?|;
940     my $sth = C4::Context->dbh->prepare($query);
941     $sth->execute($category);
942     my (@delays) = $sth->fetchrow_array;
943     return (@delays);
944 }
945
946 =head2 GetBranchcodesWithOverdueRules
947
948 =over 4
949
950 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
951
952 returns a list of branch codes for branches with overdue rules defined.
953
954 =back
955
956 =cut
957
958 sub GetBranchcodesWithOverdueRules {
959     my $dbh               = C4::Context->dbh;
960     my $rqoverduebranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode <> ''");
961     $rqoverduebranches->execute;
962     my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
963     return @branches;
964 }
965
966 =head2 CheckAccountLineLevelInfo
967
968 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
969
970 Check and Returns the list of all overdue books.
971
972 C<$exist> contains number of line in accounlines
973 with the same .biblionumber,itemnumber,accounttype,and notify_level
974
975 C<$borrowernumber> contains the borrower number
976
977 C<$itemnumber> contains item number
978
979 C<$accounttype> contains account type
980
981 C<$notify_level> contains the accountline level 
982
983
984 =cut
985
986 sub CheckAccountLineLevelInfo {
987     my ( $borrowernumber, $itemnumber, $level ) = @_;
988     my $dbh   = C4::Context->dbh;
989     my $query = qq|SELECT count(*)
990             FROM accountlines
991             WHERE borrowernumber =?
992             AND itemnumber = ?
993             AND notify_level=?|;
994     my $sth = $dbh->prepare($query);
995     $sth->execute( $borrowernumber, $itemnumber, $level );
996     my ($exist) = $sth->fetchrow;
997     return ($exist);
998 }
999
1000 =head2 GetOverduerules
1001
1002 ($overduerules) = &GetOverduerules($categorycode);
1003
1004 Returns the value of borrowers (debarred or not) with notify level
1005
1006 C<$overduerules> return value of debbraed field in overduerules table
1007
1008 C<$category> contains the borrower categorycode
1009
1010 C<$notify_level> contains the notify level
1011
1012 =cut
1013
1014 sub GetOverduerules {
1015     my ( $category, $notify_level ) = @_;
1016     my $dbh   = C4::Context->dbh;
1017     my $query = qq|SELECT debarred$notify_level
1018                      FROM overduerules
1019                     WHERE categorycode=?|;
1020     my $sth = $dbh->prepare($query);
1021     $sth->execute($category);
1022     my ($overduerules) = $sth->fetchrow;
1023     return ($overduerules);
1024 }
1025
1026
1027 =head2 CheckBorrowerDebarred
1028
1029 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1030
1031 Check if the borrowers is already debarred
1032
1033 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1034
1035 C<$borrowernumber> contains the borrower number
1036
1037 =cut
1038
1039 # FIXME: Shouldn't this be in C4::Members?
1040 sub CheckBorrowerDebarred {
1041     my ($borrowernumber) = @_;
1042     my $dbh   = C4::Context->dbh;
1043     my $query = qq|
1044         SELECT debarred
1045         FROM borrowers
1046         WHERE borrowernumber=?
1047     |;
1048     my $sth = $dbh->prepare($query);
1049     $sth->execute($borrowernumber);
1050     my ($debarredstatus) = $sth->fetchrow;
1051     return ( $debarredstatus eq '1' ? 1 : 0 );
1052 }
1053
1054 =head2 UpdateBorrowerDebarred
1055
1056 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
1057
1058 update status of borrowers in borrowers table (field debarred)
1059
1060 C<$borrowernumber> borrower number
1061
1062 =cut
1063
1064 sub UpdateBorrowerDebarred{
1065     my($borrowernumber) = @_;
1066     my $dbh = C4::Context->dbh;
1067         my $query=qq|UPDATE borrowers
1068              SET debarred='1'
1069                      WHERE borrowernumber=?
1070             |;
1071     my $sth=$dbh->prepare($query);
1072         $sth->execute($borrowernumber);
1073         $sth->finish;
1074         return 1;
1075 }
1076
1077 =head2 CheckExistantNotifyid
1078
1079   ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1080
1081 Check and Returns the notify id if exist else return 0.
1082
1083 C<$exist> contains a notify_id 
1084
1085 C<$borrowernumber> contains the borrower number
1086
1087 C<$date_due> contains the date of item return 
1088
1089
1090 =cut
1091
1092 sub CheckExistantNotifyid {
1093     my ( $borrowernumber, $date_due ) = @_;
1094     my $dbh   = C4::Context->dbh;
1095     my $query = qq|SELECT notify_id FROM accountlines
1096              LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1097              WHERE accountlines.borrowernumber =?
1098               AND date_due = ?|;
1099     my $sth = $dbh->prepare($query);
1100     $sth->execute( $borrowernumber, $date_due );
1101     return $sth->fetchrow || 0;
1102 }
1103
1104 =head2 CheckAccountLineItemInfo
1105
1106   ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1107
1108 Check and Returns the list of all overdue items from the same file number(notify_id).
1109
1110 C<$exist> contains number of line in accounlines
1111 with the same .biblionumber,itemnumber,accounttype,notify_id
1112
1113 C<$borrowernumber> contains the borrower number
1114
1115 C<$itemnumber> contains item number
1116
1117 C<$accounttype> contains account type
1118
1119 C<$notify_id> contains the file number 
1120
1121 =cut
1122
1123 sub CheckAccountLineItemInfo {
1124     my ( $borrowernumber, $itemnumber, $accounttype, $notify_id ) = @_;
1125     my $dbh   = C4::Context->dbh;
1126     my $query = qq|SELECT count(*) FROM accountlines
1127              WHERE borrowernumber =?
1128              AND itemnumber = ?
1129               AND accounttype= ?
1130             AND notify_id = ?|;
1131     my $sth = $dbh->prepare($query);
1132     $sth->execute( $borrowernumber, $itemnumber, $accounttype, $notify_id );
1133     my ($exist) = $sth->fetchrow;
1134     return ($exist);
1135 }
1136
1137 =head2 CheckItemNotify
1138
1139 Sql request to check if the document has alreday been notified
1140 this function is not exported, only used with GetOverduesForBranch
1141
1142 =cut
1143
1144 sub CheckItemNotify {
1145     my ($notify_id,$notify_level,$itemnumber) = @_;
1146     my $dbh = C4::Context->dbh;
1147     my $sth = $dbh->prepare("
1148     SELECT COUNT(*)
1149      FROM notifys
1150     WHERE notify_id    = ?
1151      AND  notify_level = ? 
1152      AND  itemnumber   = ? ");
1153     $sth->execute($notify_id,$notify_level,$itemnumber);
1154     my $notified = $sth->fetchrow;
1155     return ($notified);
1156 }
1157
1158 =head2 GetOverduesForBranch
1159
1160 Sql request for display all information for branchoverdues.pl
1161 2 possibilities : with or without location .
1162 display is filtered by branch
1163
1164 FIXME: This function should be renamed.
1165
1166 =cut
1167
1168 sub GetOverduesForBranch {
1169     my ( $branch, $location) = @_;
1170         my $itype_link =  (C4::Context->preference('item-level_itypes')) ?  " items.itype " :  " biblioitems.itemtype ";
1171     my $dbh = C4::Context->dbh;
1172     my $select = "
1173     SELECT
1174             borrowers.borrowernumber,
1175             borrowers.surname,
1176             borrowers.firstname,
1177             borrowers.phone,
1178             borrowers.email,
1179                biblio.title,
1180                biblio.biblionumber,
1181                issues.date_due,
1182                issues.returndate,
1183                issues.branchcode,
1184              branches.branchname,
1185                 items.barcode,
1186                 items.itemcallnumber,
1187                 items.location,
1188                 items.itemnumber,
1189             itemtypes.description,
1190          accountlines.notify_id,
1191          accountlines.notify_level,
1192          accountlines.amountoutstanding
1193     FROM  accountlines
1194     LEFT JOIN issues      ON    issues.itemnumber     = accountlines.itemnumber
1195                           AND   issues.borrowernumber = accountlines.borrowernumber
1196     LEFT JOIN borrowers   ON borrowers.borrowernumber = accountlines.borrowernumber
1197     LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
1198     LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
1199     LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1200     LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
1201     LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
1202     WHERE (accountlines.amountoutstanding  != '0.000000')
1203       AND (accountlines.accounttype         = 'FU'      )
1204       AND (issues.branchcode =  ?   )
1205       AND (issues.date_due  < CURDATE())
1206     ";
1207     my @getoverdues;
1208     my $i = 0;
1209     my $sth;
1210     if ($location) {
1211         $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1212         $sth->execute($branch, $location);
1213     } else {
1214         $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1215         $sth->execute($branch);
1216     }
1217     while ( my $data = $sth->fetchrow_hashref ) {
1218     #check if the document has already been notified
1219         my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1220         if ($countnotify eq '0') {
1221             $getoverdues[$i] = $data;
1222             $i++;
1223         }
1224     }
1225     return (@getoverdues);
1226 }
1227
1228
1229 =head2 AddNotifyLine
1230
1231 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1232
1233 Creat a line into notify, if the method is phone, the notification_send_date is implemented to
1234
1235 =cut
1236
1237 sub AddNotifyLine {
1238     my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1239     my $dbh = C4::Context->dbh;
1240     if ( $method eq "phone" ) {
1241         my $sth = $dbh->prepare(
1242             "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1243         VALUES (?,?,now(),now(),?,?,?)"
1244         );
1245         $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1246             $notifyId );
1247     }
1248     else {
1249         my $sth = $dbh->prepare(
1250             "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1251         VALUES (?,?,now(),?,?,?)"
1252         );
1253         $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1254             $notifyId );
1255     }
1256     return 1;
1257 }
1258
1259 =head2 RemoveNotifyLine
1260
1261 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1262
1263 Cancel a notification
1264
1265 =cut
1266
1267 sub RemoveNotifyLine {
1268     my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1269     my $dbh = C4::Context->dbh;
1270     my $sth = $dbh->prepare(
1271         "DELETE FROM notifys 
1272             WHERE
1273             borrowernumber=?
1274             AND itemnumber=?
1275             AND notify_date=?"
1276     );
1277     $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1278     return 1;
1279 }
1280
1281 1;
1282 __END__
1283
1284 =head1 AUTHOR
1285
1286 Koha Developement team <info@koha.org>
1287
1288 =cut