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