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