fixing help feature with new template structure
[koha.git] / C4 / Circulation / Fines.pm
1 package C4::Circulation::Fines;
2
3 # $Id$
4
5 # Copyright 2000-2002 Katipo Communications
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use strict;
23 require Exporter;
24 use C4::Context;
25 use Date::Calc qw/Today/;
26 use vars qw($VERSION @ISA @EXPORT);
27 use C4::Accounts;
28 use Date::Manip qw/UnixDate/;
29 use C4::Log; # logaction
30
31 # set the version for version checking
32 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; 
33 shift(@v) . "." . join("_", map {sprintf "%03d", $_ } @v); };
34
35 =head1 NAME
36
37 C4::Circulation::Fines - Koha module dealing with fines
38
39 =head1 SYNOPSIS
40
41   use C4::Overdues;
42
43 =head1 DESCRIPTION
44
45 This module contains several functions for dealing with fines for
46 overdue items. It is primarily used by the 'misc/fines2.pl' script.
47
48 =head1 FUNCTIONS
49
50 =over 2
51
52 =cut
53
54 @ISA    = qw(Exporter);
55 # subs to rename (and maybe merge some...)
56 push @EXPORT, qw(
57         &CalcFine
58         &Getoverdues
59         &CheckAccountLineLevelInfo
60         &CheckAccountLineItemInfo
61         &CheckExistantNotifyid
62         &GetNextIdNotify
63         &GetNotifyId
64         &NumberNotifyId
65         &AmountNotify
66         &UpdateAccountLines
67         &UpdateFine
68         &GetOverdueDelays
69         &GetOverduerules
70         &GetFine
71         &CreateItemAccountLine
72         &ReplacementCost2
73 );
74 # subs to remove
75 push @EXPORT, qw(
76         &BorType
77 );
78
79 #
80 # All subs to move : check that an equivalent don't exist already before moving
81 #
82
83 # subs to move to Circulation.pm
84 push @EXPORT, qw(
85         &GetIssuingRules
86         &GetIssuesIteminfo
87 );
88 # subs to move to Members.pm
89 push @EXPORT, qw(
90         &CheckBorrowerDebarred
91         &UpdateBorrowerDebarred
92 );
93 # subs to move to Biblio.pm
94 push @EXPORT, qw(
95         &GetItems
96         &ReplacementCost
97 );
98
99 =item Getoverdues
100
101   ($count, $overdues) = &Getoverdues();
102
103 Returns the list of all overdue books.
104
105 C<$count> is the number of elements in C<@{$overdues}>.
106
107 C<$overdues> is a reference-to-array. Each element is a
108 reference-to-hash whose keys are the fields of the issues table in the
109 Koha database.
110
111 =cut
112
113 #'
114 sub Getoverdues {
115     my $dbh = C4::Context->dbh;
116     my $sth = $dbh->prepare(
117         "Select * from issues where date_due < now() and returndate is
118   NULL order by borrowernumber "
119     );
120     $sth->execute;
121
122     # FIXME - Use push @results
123     my $i = 0;
124     my @results;
125     while ( my $data = $sth->fetchrow_hashref ) {
126         $results[$i] = $data;
127         $i++;
128     }
129     $sth->finish;
130
131     #  print @results;
132     # FIXME - Bogus API.
133     return ( $i, \@results );
134 }
135
136 =item CalcFine
137
138   ($amount, $chargename, $message) =
139     &CalcFine($itemnumber, $borrowercode, $days_overdue);
140
141 Calculates the fine for a book.
142
143 The issuingrules table in the Koha database is a fine matrix, listing
144 the penalties for each type of patron for each type of item and each branch (e.g., the
145 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
146 members might get a longer grace period between the first and second
147 reminders that a book is overdue).
148
149 The fine is calculated as follows: if it is time for the first
150 reminder, the fine is the value listed for the given (branch, item type,
151 borrower code) combination. If it is time for the second reminder, the
152 fine is doubled. Finally, if it is time to send the account to a
153 collection agency, the fine is set to 5 local monetary units (a really
154 good deal for the patron if the library is in Italy). Otherwise, the
155 fine is 0.
156
157 Note that the way this function is currently implemented, it only
158 returns a nonzero value on the notable days listed above. That is, if
159 the categoryitems entry says to send a first reminder 7 days after the
160 book is due, then if you call C<&CalcFine> 7 days after the book is
161 due, it will give a nonzero fine. If you call C<&CalcFine> the next
162 day, however, it will say that the fine is 0.
163
164 C<$itemnumber> is the book's item number.
165
166 C<$borrowercode> is the borrower code of the patron who currently has
167 the book.
168
169 C<$days_overdue> is the number of days elapsed since the book's due
170 date.
171
172 C<&CalcFine> returns a list of three values:
173
174 C<$amount> is the fine owed by the patron (see above).
175
176 C<$chargename> is the chargename field from the applicable record in
177 the categoryitem table, whatever that is.
178
179 C<$message> is a text message, either "First Notice", "Second Notice",
180 or "Final Notice".
181
182 =cut
183
184 #'
185 sub CalcFine {
186     my ( $itemnumber, $bortype, $difference , $dues  ) = @_;
187     my $dbh = C4::Context->dbh;
188     my $data = GetIssuingRules($itemnumber,$bortype);
189     my $amount = 0;
190     my $printout;
191     my $countspecialday=&GetSpecialHolidays($dues,$itemnumber);
192     my $countrepeatableday=&GetRepeatableHolidays($dues,$itemnumber,$difference);    
193     my $countalldayclosed = $countspecialday + $countrepeatableday;
194     my $daycount = $difference - $countalldayclosed;    
195     my $daycounttotal = $daycount - $data->{'firstremind'};
196         if ($data->{'firstremind'} < $daycount)
197     {
198     $amount   = $daycounttotal*$data->{'fine'};
199     }
200  return ( $amount, $data->{'chargename'}, $printout ,$daycounttotal ,$daycount );
201 }
202
203
204 =item GetSpecialHolidays
205
206 &GetSpecialHolidays($date_dues,$itemnumber);
207
208 return number of special days  between date of the day and date due
209
210 C<$date_dues> is the envisaged date of book return.
211
212 C<$itemnumber> is the book's item number.
213
214 =cut
215
216 sub GetSpecialHolidays {
217 my ($date_dues,$itemnumber) = @_;
218 # calcul the today date
219 my $today = join "-", &Today();
220
221 # return the holdingbranch
222 my $iteminfo=GetIssuesIteminfo($itemnumber);
223 # use sql request to find all date between date_due and today
224 my $dbh = C4::Context->dbh;
225 my $query=qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d')as date 
226 FROM `special_holidays`
227 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
228 AND   DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
229 AND branchcode=?
230 |;
231 my @result=GetWdayFromItemnumber($itemnumber);
232 my @result_date;
233 my $wday;
234 my $dateinsec;
235 my $sth = $dbh->prepare($query);
236 $sth->execute($date_dues,$today,$iteminfo->{'branchcode'});
237
238 while ( my $special_date=$sth->fetchrow_hashref){
239     push (@result_date,$special_date);
240 }
241
242 my $specialdaycount=scalar(@result_date);
243
244     for (my $i=0;$i<scalar(@result_date);$i++){
245         $dateinsec=UnixDate($result_date[$i]->{'date'},"%o");
246         (undef,undef,undef,undef,undef,undef,$wday,undef,undef) =localtime($dateinsec);
247         for (my $j=0;$j<scalar(@result);$j++){
248             if ($wday == ($result[$j]->{'weekday'})){
249             $specialdaycount --;
250             }
251         }
252     }
253
254 return $specialdaycount;
255 }
256
257 =item GetRepeatableHolidays
258
259 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
260
261 return number of day closed between date of the day and date due
262
263 C<$date_dues> is the envisaged date of book return.
264
265 C<$itemnumber> is item number.
266
267 C<$difference> numbers of between day date of the day and date due
268
269 =cut
270
271 sub GetRepeatableHolidays{
272 my ($date_dues,$itemnumber,$difference) = @_;
273 my $dateinsec=UnixDate($date_dues,"%o");
274 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime($dateinsec);
275 my @result=GetWdayFromItemnumber($itemnumber);
276 my @dayclosedcount;
277 my $j;
278
279 for (my $i=0;$i<scalar(@result);$i++){
280     my $k=$wday;
281
282         for ( $j=0;$j<$difference;$j++){
283             if ($result[$i]->{'weekday'} == $k)
284                     {
285                     push ( @dayclosedcount ,$k);
286             }
287         $k++;
288         ($k=0) if($k eq 7);
289         }
290     }
291 return scalar(@dayclosedcount);
292 }
293
294
295 =item GetWayFromItemnumber
296
297 &Getwdayfromitemnumber($itemnumber);
298
299 return the different week day from repeatable_holidays table
300
301 C<$itemnumber> is  item number.
302
303 =cut
304
305 sub GetWdayFromItemnumber{
306 my($itemnumber)=@_;
307 my $iteminfo=GetIssuesIteminfo($itemnumber);
308 my @result;
309 my $dbh = C4::Context->dbh;
310 my $query = qq|SELECT weekday  
311     FROM repeatable_holidays
312     WHERE branchcode=?
313 |;
314 my $sth = $dbh->prepare($query);
315     #  print $query;
316
317 $sth->execute($iteminfo->{'branchcode'});
318 while ( my $weekday=$sth->fetchrow_hashref){
319     push (@result,$weekday);
320     }
321 return @result;
322 }
323
324
325 =item GetIssuesIteminfo
326
327 &GetIssuesIteminfo($itemnumber);
328
329 return all data from issues about item
330
331 C<$itemnumber> is  item number.
332
333 =cut
334
335 sub GetIssuesIteminfo{
336 my($itemnumber)=@_;
337 my $dbh = C4::Context->dbh;
338 my $query = qq|SELECT *  
339     FROM issues
340     WHERE itemnumber=?
341     AND returndate IS NULL|;
342 my $sth = $dbh->prepare($query);
343 $sth->execute($itemnumber);
344 my ($issuesinfo)=$sth->fetchrow_hashref;
345 return $issuesinfo;
346 }
347
348
349 =item UpdateFine
350
351   &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
352
353 (Note: the following is mostly conjecture and guesswork.)
354
355 Updates the fine owed on an overdue book.
356
357 C<$itemnumber> is the book's item number.
358
359 C<$borrowernumber> is the borrower number of the patron who currently
360 has the book on loan.
361
362 C<$amount> is the current amount owed by the patron.
363
364 C<$type> will be used in the description of the fine.
365
366 C<$description> is a string that must be present in the description of
367 the fine. I think this is expected to be a date in DD/MM/YYYY format.
368
369 C<&UpdateFine> looks up the amount currently owed on the given item
370 and sets it to C<$amount>, creating, if necessary, a new entry in the
371 accountlines table of the Koha database.
372
373 =cut
374
375 #'
376 # FIXME - This API doesn't look right: why should the caller have to
377 # specify both the item number and the borrower number? A book can't
378 # be on loan to two different people, so the item number should be
379 # sufficient.
380 sub UpdateFine {
381     my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
382     my $dbh = C4::Context->dbh;
383     # FIXME - What exactly is this query supposed to do? It looks up an
384     # entry in accountlines that matches the given item and borrower
385     # numbers, where the description contains $due, and where the
386     # account type has one of several values, but what does this _mean_?
387     # Does it look up existing fines for this item?
388     # FIXME - What are these various account types? ("FU", "O", "F", "M")
389     my $sth = $dbh->prepare(
390         "Select * from accountlines where itemnumber=? and
391   borrowernumber=? and (accounttype='FU' or accounttype='O' or
392   accounttype='F' or accounttype='M') and description like ?"
393     );
394     $sth->execute( $itemnum, $borrowernumber, "%$due%" );
395
396     if ( my $data = $sth->fetchrow_hashref ) {
397
398         # I think this if-clause deals with the case where we're updating
399         # an existing fine.
400         #    print "in accounts ...";
401     if ( $data->{'amount'} != $amount ) {
402            
403         #      print "updating";
404             my $diff = $amount - $data->{'amount'};
405             my $out  = $data->{'amountoutstanding'} + $diff;
406             my $sth2 = $dbh->prepare(
407                 "update accountlines set date=now(), amount=?,
408       amountoutstanding=?,accounttype='FU' where
409       borrowernumber=? and itemnumber=?
410       and (accounttype='FU' or accounttype='O') and description like ?"
411             );
412             $sth2->execute( $amount, $out, $data->{'borrowernumber'},
413                 $data->{'itemnumber'}, "%$due%" );
414             $sth2->finish;
415         }
416         else {
417
418             #      print "no update needed $data->{'amount'}"
419         }
420     }
421     else {
422
423         # I think this else-clause deals with the case where we're adding
424         # a new fine.
425         my $sth4 = $dbh->prepare(
426             "select title from biblio,items where items.itemnumber=?
427     and biblio.biblionumber=items.biblionumber"
428         );
429         $sth4->execute($itemnum);
430         my $title = $sth4->fetchrow_hashref;
431         $sth4->finish;
432
433 #         #   print "not in account";
434 #         my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
435 #         $sth3->execute;
436
437 #         # FIXME - Make $accountno a scalar.
438 #         my @accountno = $sth3->fetchrow_array;
439 #         $sth3->finish;
440 #         $accountno[0]++;
441 # begin transaction
442   my $nextaccntno = getnextacctno($borrowernumber);
443     my $sth2 = $dbh->prepare(
444             "INSERT INTO accountlines
445     (borrowernumber,itemnumber,date,amount,
446     description,accounttype,amountoutstanding,accountno) VALUES
447     (?,?,now(),?,?,'FU',?,?)"
448         );
449         $sth2->execute( $borrowernumber, $itemnum, $amount,
450             "$type $title->{'title'} $due",
451             $amount, $nextaccntno);
452         $sth2->finish;
453     }
454     # logging action
455     &logaction(
456         C4::Context->userenv->{'number'},
457         "FINES",
458         $type,
459         $borrowernumber,
460         "due=".$due."  amount=".$amount." itemnumber=".$itemnum
461         ) if C4::Context->preference("FinesLog");
462
463     $sth->finish;
464 }
465
466 =item BorType
467
468   $borrower = &BorType($borrowernumber);
469
470 Looks up a patron by borrower number.
471
472 C<$borrower> is a reference-to-hash whose keys are all of the fields
473 from the borrowers and categories tables of the Koha database. Thus,
474 C<$borrower> contains all information about both the borrower and
475 category he or she belongs to.
476
477 =cut
478
479 #'
480 sub BorType {
481     my ($borrowernumber) = @_;
482     my $dbh              = C4::Context->dbh;
483     my $sth              = $dbh->prepare(
484         "Select * from borrowers,categories where
485   borrowernumber=? and
486 borrowers.categorycode=categories.categorycode"
487     );
488     $sth->execute($borrowernumber);
489     my $data = $sth->fetchrow_hashref;
490     $sth->finish;
491     return ($data);
492 }
493
494 =item ReplacementCost
495
496   $cost = &ReplacementCost($itemnumber);
497
498 Returns the replacement cost of the item with the given item number.
499
500 =cut
501
502 #'
503 sub ReplacementCost {
504     my ($itemnum) = @_;
505     my $dbh       = C4::Context->dbh;
506     my $sth       =
507       $dbh->prepare("Select replacementprice from items where itemnumber=?");
508     $sth->execute($itemnum);
509
510     # FIXME - Use fetchrow_array or something.
511     my $data = $sth->fetchrow_hashref;
512     $sth->finish;
513     return ( $data->{'replacementprice'} );
514 }
515
516 =item GetFine
517
518 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
519
520 return the total of fine
521
522 C<$itemnum> is item number
523
524 C<$borrowernumber> is the borrowernumber
525
526 =cut 
527
528
529 sub GetFine {
530     my ( $itemnum, $borrowernumber ) = @_;
531     my $dbh   = C4::Context->dbh();
532     my $query = "SELECT sum(amountoutstanding) FROM accountlines 
533     where accounttype like 'F%'  
534   AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
535     my $sth = $dbh->prepare($query);
536     $sth->execute( $itemnum, $borrowernumber );
537     my $data = $sth->fetchrow_hashref();
538     $sth->finish();
539     $dbh->disconnect();
540     return ( $data->{'sum(amountoutstanding)'} );
541 }
542
543
544
545
546 =item GetIssuingRules
547
548 $data = &GetIssuingRules($itemnumber,$categorycode);
549
550 Looks up for all issuingrules an item info 
551
552 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
553 from the borrowers and categories tables of the Koha database. Thus,
554
555 C<$categorycode> contains  information about borrowers category 
556
557 C<$data> contains all information about both the borrower and
558 category he or she belongs to.
559 =cut 
560
561 sub GetIssuingRules {
562    my ($itemnumber,$categorycode)=@_;
563    my $dbh   = C4::Context->dbh();    
564    my $query=qq|SELECT * 
565         FROM items,biblioitems,itemtypes,issuingrules
566         WHERE items.itemnumber=?
567         AND items.biblioitemnumber=biblioitems.biblioitemnumber
568         AND biblioitems.itemtype=itemtypes.itemtype
569         AND issuingrules.itemtype=itemtypes.itemtype
570         AND issuingrules.categorycode=?
571         AND  (items.itemlost <> 1
572         OR items.itemlost is NULL)|;
573     my $sth = $dbh->prepare($query);
574     #  print $query;
575     $sth->execute($itemnumber,$categorycode);
576     my ($data) = $sth->fetchrow_hashref;
577    $sth->finish;
578 return ($data);
579
580 }
581
582
583 sub ReplacementCost2 {
584     my ( $itemnum, $borrowernumber ) = @_;
585     my $dbh   = C4::Context->dbh();
586     my $query = "SELECT amountoutstanding 
587          FROM accountlines
588              WHERE accounttype like 'L'
589          AND amountoutstanding > 0
590          AND itemnumber = ?
591          AND borrowernumber= ?";
592     my $sth = $dbh->prepare($query);
593     $sth->execute( $itemnum, $borrowernumber );
594     my $data = $sth->fetchrow_hashref();
595     $sth->finish();
596     $dbh->disconnect();
597     return ( $data->{'amountoutstanding'} );
598 }
599
600
601 =item GetNextIdNotify
602
603 ($result) = &GetNextIdNotify($reference);
604
605 Returns the new file number
606
607 C<$result> contains the next file number
608
609 C<$reference> contains the beggining of file number
610
611 =cut
612
613
614
615 sub GetNextIdNotify {
616 my ($reference)=@_;
617 my $query=qq|SELECT max(notify_id) 
618          FROM accountlines
619          WHERE notify_id  like \"$reference%\"
620          |;
621 # AND borrowernumber=?|;   
622 my $dbh = C4::Context->dbh;
623 my $sth=$dbh->prepare($query);
624 $sth->execute();
625 my $result=$sth->fetchrow;
626 $sth->finish;
627 my $count;
628     if ($result eq '')
629     {
630     ($result=$reference."01")  ;
631     }else
632     {
633     $count=substr($result,6)+1;
634      
635     if($count<10){
636      ($count = "0".$count);
637      }
638      $result=$reference.$count;
639      }
640 return $result;
641 }
642
643
644 =item AmountNotify
645
646 (@notify) = &AmountNotify($borrowernumber);
647
648 Returns amount for all file per borrowers
649 C<@notify> array contains all file per borrowers
650
651 C<$notify_id> contains the file number for the borrower number nad item number
652
653 =cut
654
655 sub NumberNotifyId{
656     my ($borrowernumber)=@_;
657     my $dbh = C4::Context->dbh;
658     my $query=qq|    SELECT distinct(notify_id)
659             FROM accountlines
660             WHERE borrowernumber=?
661             AND notify_id != 0
662             AND notify_id != 1  |;
663     my @notify;
664     my $sth=$dbh->prepare($query);
665         $sth->execute($borrowernumber);
666           while ( my $numberofotify=$sth->fetchrow_array){
667     push (@notify,$numberofotify);
668     }
669     $sth->finish;
670
671     return (@notify);
672
673 }
674
675 =item AmountNotify
676
677 ($totalnotify) = &AmountNotify($notifyid);
678
679 Returns amount for all file per borrowers
680 C<$notifyid> is the file number
681
682 C<$totalnotify> contains amount of a file
683
684 C<$notify_id> contains the file number for the borrower number nad item number
685
686 =cut
687
688 sub AmountNotify{
689     my ($notifyid)=@_;
690     my $dbh = C4::Context->dbh;
691     my $query=qq|    SELECT sum(amountoutstanding)
692             FROM accountlines
693             WHERE notify_id=?|;
694     my $sth=$dbh->prepare($query);
695         $sth->execute($notifyid);
696           my $totalnotify=$sth->fetchrow;
697     $sth->finish;
698     return ($totalnotify);
699 }
700
701
702 =item GetNotifyId
703
704 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
705
706 Returns the file number per borrower and itemnumber
707
708 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
709 from the items tables of the Koha database. Thus,
710
711 C<$itemnumber> contains the borrower categorycode
712
713 C<$notify_id> contains the file number for the borrower number nad item number
714
715 =cut
716
717  sub GetNotifyId {
718  my ($borrowernumber,$itemnumber)=@_;
719  my $query=qq|SELECT notify_id 
720            FROM accountlines
721            WHERE borrowernumber=?
722           AND itemnumber=?
723            AND (accounttype='FU' or accounttype='O')|;
724  my $dbh = C4::Context->dbh;
725  my $sth=$dbh->prepare($query);
726  $sth->execute($borrowernumber,$itemnumber);
727  my ($notify_id)=$sth->fetchrow;
728  $sth->finish;
729  return ($notify_id);
730
731  }
732
733 =item CreateItemAccountLine
734
735 () = &CreateItemAccountLine($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
736
737 update the account lines with file number or with file level
738
739 C<$items> is a reference-to-hash whose keys are all of the fields
740 from the items tables of the Koha database. Thus,
741
742 C<$itemnumber> contains the item number
743
744 C<$borrowernumber> contains the borrower number
745
746 C<$date> contains the date of the day
747
748 C<$amount> contains item price
749
750 C<$description> contains the descritpion of accounttype 
751
752 C<$accounttype> contains the account type
753
754 C<$amountoutstanding> contains the $amountoutstanding 
755
756 C<$timestamp> contains the timestamp with time and the date of the day
757
758 C<$notify_id> contains the file number
759
760 C<$level> contains the file level
761
762
763 =cut
764
765  sub CreateItemAccountLine {
766   my ($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level)=@_;
767   my $dbh = C4::Context->dbh;
768   my $nextaccntno = getnextacctno($borrowernumber);
769    my $query= "INSERT into accountlines  
770          (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
771           VALUES
772              (?,?,?,?,?,?,?,?,?,?,?)";
773   
774   
775   my $sth=$dbh->prepare($query);
776   $sth->execute($borrowernumber,$nextaccntno,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
777   $sth->finish;
778  }
779
780 =item UpdateAccountLines
781
782 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
783
784 update the account lines with file number or with file level
785
786 C<$items> is a reference-to-hash whose keys are all of the fields
787 from the items tables of the Koha database. Thus,
788
789 C<$itemnumber> contains the item number
790
791 C<$notify_id> contains the file number
792
793 C<$notify_level> contains the file level
794
795 C<$borrowernumber> contains the borrowernumber
796
797 =cut
798
799 sub UpdateAccountLines {
800 my ($notify_id,$notify_level,$borrowernumber,$itemnumber)=@_;
801 my $query;
802 if ($notify_id eq '')
803 {
804
805     $query=qq|UPDATE accountlines
806     SET  notify_level=?
807     WHERE borrowernumber=? AND itemnumber=?
808     AND (accounttype='FU' or accounttype='O')|;
809 }else
810 {
811     $query=qq|UPDATE accountlines
812      SET notify_id=?, notify_level=?
813            WHERE borrowernumber=?
814     AND itemnumber=?
815         AND (accounttype='FU' or accounttype='O')|;
816 }
817  my $dbh = C4::Context->dbh;
818  my $sth=$dbh->prepare($query);
819
820 if ($notify_id eq '')
821 {
822     $sth->execute($notify_level,$borrowernumber,$itemnumber);
823 }else
824 {
825     $sth->execute($notify_id,$notify_level,$borrowernumber,$itemnumber);
826 }
827  $sth->finish;
828
829 }
830
831
832 =item GetItems
833
834 ($items) = &GetItems($itemnumber);
835
836 Returns the list of all delays from overduerules.
837
838 C<$items> is a reference-to-hash whose keys are all of the fields
839 from the items tables of the Koha database. Thus,
840
841 C<$itemnumber> contains the borrower categorycode
842
843 =cut
844
845 sub GetItems {
846     my($itemnumber) = @_;
847     my $query=qq|SELECT *
848              FROM items
849               WHERE itemnumber=?|;
850         my $dbh = C4::Context->dbh;
851         my $sth=$dbh->prepare($query);
852         $sth->execute($itemnumber);
853         my ($items)=$sth->fetchrow_hashref;
854         $sth->finish;
855     return($items);
856 }
857
858 =item GetOverdueDelays
859
860 (@delays) = &GetOverdueDelays($categorycode);
861
862 Returns the list of all delays from overduerules.
863
864 C<@delays> it's an array contains the three delays from overduerules table
865
866 C<$categorycode> contains the borrower categorycode
867
868 =cut
869
870 sub GetOverdueDelays {
871     my($category) = @_;
872     my $dbh = C4::Context->dbh;
873         my $query=qq|SELECT delay1,delay2,delay3
874                 FROM overduerules
875                 WHERE categorycode=?|;
876     my $sth=$dbh->prepare($query);
877         $sth->execute($category);
878         my (@delays)=$sth->fetchrow_array;
879         $sth->finish;
880         return(@delays);
881 }
882
883 =item CheckAccountLineLevelInfo
884
885 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
886
887 Check and Returns the list of all overdue books.
888
889 C<$exist> contains number of line in accounlines
890 with the same .biblionumber,itemnumber,accounttype,and notify_level
891
892 C<$borrowernumber> contains the borrower number
893
894 C<$itemnumber> contains item number
895
896 C<$accounttype> contains account type
897
898 C<$notify_level> contains the accountline level 
899
900
901 =cut
902
903 sub CheckAccountLineLevelInfo {
904     my($borrowernumber,$itemnumber,$level,$datedue) = @_;
905         my @formatdate;
906         @formatdate=split('-',$datedue);
907         $datedue=$formatdate[2]."/".$formatdate[1]."/".$formatdate[0];
908         my $dbh = C4::Context->dbh;
909         my $query=      qq|SELECT count(*) 
910                         FROM accountlines 
911                         WHERE borrowernumber =?
912                         AND itemnumber = ?
913                         AND notify_level=?
914                         AND description like ?|;
915         my $sth=$dbh->prepare($query);
916         $sth->execute($borrowernumber,$itemnumber,$level,"%$datedue%");
917         my ($exist)=$sth->fetchrow;
918         $sth->finish;
919         return($exist);
920 }
921
922 =item GetOverduerules
923
924 ($overduerules) = &GetOverduerules($categorycode);
925
926 Returns the value of borrowers (debarred or not) with notify level
927
928 C<$overduerules> return value of debbraed field in overduerules table
929
930 C<$category> contains the borrower categorycode
931
932 C<$notify_level> contains the notify level
933 =cut
934
935
936 sub GetOverduerules{
937     my($category,$notify_level) = @_;
938     my $dbh = C4::Context->dbh;
939         my $query=qq|SELECT debarred$notify_level
940              FROM overduerules
941              WHERE categorycode=?|;
942     my $sth=$dbh->prepare($query);
943         $sth->execute($category);
944         my ($overduerules)=$sth->fetchrow;
945         $sth->finish;
946         return($overduerules);
947 }
948
949
950 =item CheckBorrowerDebarred
951
952 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
953
954 Check if the borrowers is already debarred
955
956 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
957
958 C<$borrowernumber> contains the borrower number
959
960 =cut
961
962
963 sub CheckBorrowerDebarred{
964     my($borrowernumber) = @_;
965     my $dbh = C4::Context->dbh;
966         my $query=qq|SELECT debarred
967               FROM borrowers
968              WHERE borrowernumber=?
969             |;
970     my $sth=$dbh->prepare($query);
971         $sth->execute($borrowernumber);
972         my ($debarredstatus)=$sth->fetchrow;
973         $sth->finish;
974         if ($debarredstatus eq '1'){
975     return(1);}
976     else{
977     return(0);
978     }
979 }
980
981 =item UpdateBorrowerDebarred
982
983 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
984
985 update status of borrowers in borrowers table (field debarred)
986
987 C<$borrowernumber> borrower number
988
989 =cut
990
991 sub UpdateBorrowerDebarred{
992     my($borrowernumber) = @_;
993     my $dbh = C4::Context->dbh;
994         my $query=qq|UPDATE borrowers
995              SET debarred='1'
996                      WHERE borrowernumber=?
997             |;
998     my $sth=$dbh->prepare($query);
999         $sth->execute($borrowernumber);
1000         $sth->finish;
1001         return 1;
1002 }
1003
1004 =item CheckExistantNotifyid
1005
1006   ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1007
1008 Check and Returns the notify id if exist else return 0.
1009
1010 C<$exist> contains a notify_id 
1011
1012 C<$borrowernumber> contains the borrower number
1013
1014 C<$date_due> contains the date of item return 
1015
1016
1017 =cut
1018
1019 sub CheckExistantNotifyid {
1020     my($borrowernumber,$date_due) = @_;
1021         my $dbh = C4::Context->dbh;
1022         my @formatdate;
1023         @formatdate=split('-',$date_due);
1024         $date_due=$formatdate[2]."/".$formatdate[1]."/".$formatdate[0];
1025         my $query =  qq|SELECT notify_id FROM accountlines 
1026                         WHERE description like ?
1027                         AND borrowernumber =?
1028                         AND( accounttype='FU'  OR accounttype='F' )
1029                            AND notify_id != 0
1030                         AND notify_id != 1|;
1031         my $sth=$dbh->prepare($query);
1032         $sth->execute("%$date_due%",$borrowernumber);
1033         my ($exist)=$sth->fetchrow;
1034         $sth->finish;
1035         if ($exist eq '')
1036         {
1037         return(0);
1038         }else
1039             {
1040         return($exist);
1041         }
1042 }
1043
1044 =item CheckAccountLineItemInfo
1045
1046   ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1047
1048 Check and Returns the list of all overdue items from the same file number(notify_id).
1049
1050 C<$exist> contains number of line in accounlines
1051 with the same .biblionumber,itemnumber,accounttype,notify_id
1052
1053 C<$borrowernumber> contains the borrower number
1054
1055 C<$itemnumber> contains item number
1056
1057 C<$accounttype> contains account type
1058
1059 C<$notify_id> contains the file number 
1060
1061 =cut
1062
1063 sub CheckAccountLineItemInfo {
1064      my($borrowernumber,$itemnumber,$accounttype,$notify_id) = @_;
1065      my $dbh = C4::Context->dbh;
1066          my $query =  qq|SELECT count(*) FROM accountlines
1067              WHERE borrowernumber =?
1068              AND itemnumber = ?
1069               AND accounttype= ?
1070             AND notify_id = ?|;
1071     my $sth=$dbh->prepare($query);
1072          $sth->execute($borrowernumber,$itemnumber,$accounttype,$notify_id);
1073          my ($exist)=$sth->fetchrow;
1074          $sth->finish;
1075          return($exist);
1076  }
1077
1078
1079 1;
1080 __END__
1081
1082 =back
1083
1084 =head1 AUTHOR
1085
1086 Koha Developement team <info@koha.org>
1087
1088 =cut