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