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