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