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