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