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