4 # Copyright 2000-2002 Katipo Communications
6 # This file is part of Koha.
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
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.
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
22 use Date::Calc qw/Today Date_to_Days/;
23 use C4::Dates qw/format_date/;
24 use Date::Manip qw/UnixDate/;
28 use C4::Log; # logaction
31 use vars qw($VERSION @ISA @EXPORT);
34 # set the version for version checking
38 # subs to rename (and maybe merge some...)
43 &CheckAccountLineLevelInfo
44 &CheckAccountLineItemInfo
45 &CheckExistantNotifyid
54 &GetOverduesByBorrowers
56 &CreateItemAccountLine
69 # check that an equivalent don't exist already before moving
71 # subs to move to Circulation.pm
76 # &GetIssuingRules - delete.
77 # use C4::Circulation::GetIssuingRule instead.
79 # subs to move to Members.pm
81 &CheckBorrowerDebarred
82 &UpdateBorrowerDebarred
84 # subs to move to Biblio.pm
93 C4::Circulation::Fines - Koha module dealing with fines
101 This module contains several functions for dealing with fines for
102 overdue items. It is primarily used by the 'misc/fines2.pl' script.
108 $overdues = Getoverdues( { minimumdays => 1, maximumdays => 30 } );
110 Returns the list of all overdue books, with their itemtype.
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
121 my $dbh = C4::Context->dbh;
123 if ( C4::Context->preference('item-level_itypes') ) {
125 SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode
127 LEFT JOIN items USING (itemnumber)
128 WHERE date_due < now()
132 SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode
134 LEFT JOIN items USING (itemnumber)
135 LEFT JOIN biblioitems USING (biblioitemnumber)
136 WHERE date_due < now()
141 if ( exists $params->{'minimumdays'} and exists $params->{'maximumdays'} ) {
142 $statement .= ' AND TO_DAYS( NOW() )-TO_DAYS( date_due ) BETWEEN ? and ? ';
143 push @bind_parameters, $params->{'minimumdays'}, $params->{'maximumdays'};
144 } elsif ( exists $params->{'minimumdays'} ) {
145 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) > ? ';
146 push @bind_parameters, $params->{'minimumdays'};
147 } elsif ( exists $params->{'maximumdays'} ) {
148 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ? ';
149 push @bind_parameters, $params->{'maximumdays'};
151 $statement .= 'ORDER BY borrowernumber';
152 my $sth = $dbh->prepare( $statement );
153 $sth->execute( @bind_parameters );
154 return $sth->fetchall_arrayref({});
157 =head2 GetOverduesByBorrowers
159 @borrowers = GetOverduesByBorrowers();
161 Returns an array with hashes, that contains all informations of borrowers, and another hash with overdues
168 'borrowernumber' => ,
190 sub GetOverduesByBorrowers{
191 my ($branchcode, $category, $itemtype, $flags, $name, $order, $dateduefrom, $datedueto) = @_;
194 my $dbh = C4::Context->dbh;
202 CONCAT(borrowers.address, '\n', borrowers.address2) as address,
212 WHERE borrowernumber IN (SELECT distinct(borrowernumber) FROM issues WHERE date_due < NOW() )
214 $strsth.=" AND (borrowers.firstname like '".$name."%' or borrowers.surname like '".$name."%' or borrowers.cardnumber like '".$name."%')" if($name) ;
215 $strsth.=" AND borrowers.categorycode = '" . $category . "' " if $category;
216 $strsth.=" AND borrowers.flags = '" . $flags . "' " if $flags;
217 $strsth.=" AND borrowers.branchcode = '" . $branchcode . "' " if $branchcode;
219 $strsth.=" ORDER BY " . (
220 ($order eq "surname" or $order eq "surname desc") ? "$order" :
221 ($order eq "title" or $order eq "title desc") ? "$order, surname" :
222 "surname" # default sort order
238 LEFT JOIN items USING(itemnumber)
239 LEFT JOIN biblio USING(biblionumber)
240 LEFT JOIN biblioitems USING(biblionumber)
246 my $itype = (C4::Context->preference("item-level_itypes")) ? "itype" : "itemtype" ;
248 $strsthissues .= " AND $itype = ? ";
249 push @args, $itemtype;
252 $strsthissues .= " AND date_due < ? ";
253 push @args, $datedueto;
256 $strsthissues .= " AND date_due > ? ";
257 push @args, $dateduefrom;
259 if(not ($datedueto or $dateduefrom)){
260 $strsthissues .= " AND date_due < NOW() ";
262 my $sthissues = $dbh->prepare($strsthissues);
263 my $sthbor = $dbh->prepare($strsth);
266 while (my $data=$sthbor->fetchrow_hashref) {
267 my $borrower = $data;
268 $sthissues->execute($data->{borrowernumber}, @args);
271 while(my $issuedata = $sthissues->fetchrow_hashref()){
272 $issuedata->{date_due} = format_date($issuedata->{date_due});
273 $issuedata->{issuedate} = format_date($issuedata->{issuedate});
274 push @issues, $issuedata;
276 $borrower->{overdues} = \@issues;
277 push @result, $borrower if scalar @{$borrower->{overdues}};
284 ($count, $overdueitems) = checkoverdues($borrowernumber);
286 Returns a count and a list of overdueitems for a given borrowernumber
291 my $borrowernumber = shift or return;
292 my $sth = C4::Context->dbh->prepare(
293 "SELECT * FROM issues
294 LEFT JOIN items ON issues.itemnumber = items.itemnumber
295 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
296 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
297 WHERE issues.borrowernumber = ?
298 AND issues.date_due < CURDATE()"
300 # FIXME: SELECT * across 4 tables? do we really need the marc AND marcxml blobs??
301 $sth->execute($borrowernumber);
302 my $results = $sth->fetchall_arrayref({});
303 return ( scalar(@$results), $results); # returning the count and the results is silly
308 ($amount, $chargename, $daycount, $daycounttotal) =
309 &CalcFine($item, $categorycode, $branch, $days_overdue, $description, $start_date, $end_date );
311 Calculates the fine for a book.
313 The issuingrules table in the Koha database is a fine matrix, listing
314 the penalties for each type of patron for each type of item and each branch (e.g., the
315 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
316 members might get a longer grace period between the first and second
317 reminders that a book is overdue).
320 C<$item> is an item object (hashref).
322 C<$categorycode> is the category code (string) of the patron who currently has
325 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
327 C<$days_overdue> is the number of days elapsed since the book's due date.
328 NOTE: supplying days_overdue is deprecated.
330 C<$start_date> & C<$end_date> are C4::Dates objects
331 defining the date range over which to determine the fine.
332 Note that if these are defined, we ignore C<$difference> and C<$dues> ,
333 but retain these for backwards-comptibility with extant fines scripts.
335 Fines scripts should just supply the date range over which to calculate the fine.
337 C<&CalcFine> returns four values:
339 C<$amount> is the fine owed by the patron (see above).
341 C<$chargename> is the chargename field from the applicable record in
342 the categoryitem table, whatever that is.
344 C<$daycount> is the number of days between start and end dates, Calendar adjusted (where needed),
345 minus any applicable grace period.
347 C<$daycounttotal> is C<$daycount> without consideration of grace period.
349 FIXME - What is chargename supposed to be ?
351 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
352 or "Final Notice". But CalcFine never defined any value.
357 my ( $item, $bortype, $branchcode, $difference ,$dues , $start_date, $end_date ) = @_;
358 $debug and warn sprintf("CalcFine(%s, %s, %s, %s, %s, %s, %s)",
359 ($item ? '{item}' : 'UNDEF'),
360 ($bortype || 'UNDEF'),
361 ($branchcode || 'UNDEF'),
362 ($difference || 'UNDEF'),
364 ($start_date ? ($start_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF'),
365 ( $end_date ? ( $end_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF')
367 my $dbh = C4::Context->dbh;
370 # get issuingrules (fines part will be used)
371 $debug and warn sprintf("CalcFine calling GetIssuingRule(%s, %s, %s)", $bortype, $item->{'itemtype'}, $branchcode);
372 my $data = C4::Circulation::GetIssuingRule($bortype, $item->{'itemtype'}, $branchcode);
374 # if $difference is supplied, the difference has already been calculated, but we still need to adjust for the calendar.
375 # use copy-pasted functions from calendar module. (deprecated -- these functions will be removed from C4::Overdues ).
376 my $countspecialday = &GetSpecialHolidays($dues,$item->{itemnumber});
377 my $countrepeatableday = &GetRepeatableHolidays($dues,$item->{itemnumber},$difference);
378 my $countalldayclosed = $countspecialday + $countrepeatableday;
379 $daystocharge = $difference - $countalldayclosed;
381 # if $difference is not supplied, we have C4::Dates objects giving us the date range, and we use the calendar module.
382 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
383 my $calendar = C4::Calendar->new( branchcode => $branchcode );
384 $daystocharge = $calendar->daysBetween( $start_date, $end_date );
386 $daystocharge = Date_to_Days(split('-',$end_date->output('iso'))) - Date_to_Days(split('-',$start_date->output('iso')));
389 # correct for grace period.
390 my $days_minus_grace = $daystocharge - $data->{'firstremind'};
391 if ($data->{'chargeperiod'} > 0 && $days_minus_grace > 0 ) {
392 $amount = int($days_minus_grace / $data->{'chargeperiod'}) * $data->{'fine'};
394 # a zero (or null) chargeperiod means no charge.
396 $amount = C4::Context->preference('maxFine') if(C4::Context->preference('maxFine') && ( $amount > C4::Context->preference('maxFine')));
397 $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
398 return ($amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
399 # FIXME: chargename is NEVER populated anywhere.
403 =head2 GetSpecialHolidays
405 &GetSpecialHolidays($date_dues,$itemnumber);
407 return number of special days between date of the day and date due
409 C<$date_dues> is the envisaged date of book return.
411 C<$itemnumber> is the book's item number.
415 sub GetSpecialHolidays {
416 my ( $date_dues, $itemnumber ) = @_;
418 # calcul the today date
419 my $today = join "-", &Today();
421 # return the holdingbranch
422 my $iteminfo = GetIssuesIteminfo($itemnumber);
424 # use sql request to find all date between date_due and today
425 my $dbh = C4::Context->dbh;
427 qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
428 FROM `special_holidays`
429 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
430 AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
433 my @result = GetWdayFromItemnumber($itemnumber);
437 my $sth = $dbh->prepare($query);
438 $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
439 ; # FIXME: just use NOW() in SQL instead of passing in $today
441 while ( my $special_date = $sth->fetchrow_hashref ) {
442 push( @result_date, $special_date );
445 my $specialdaycount = scalar(@result_date);
447 for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
448 $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
449 ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
450 localtime($dateinsec);
451 for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
452 if ( $wday == ( $result[$j]->{'weekday'} ) ) {
458 return $specialdaycount;
461 =head2 GetRepeatableHolidays
463 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
465 return number of day closed between date of the day and date due
467 C<$date_dues> is the envisaged date of book return.
469 C<$itemnumber> is item number.
471 C<$difference> numbers of between day date of the day and date due
475 sub GetRepeatableHolidays {
476 my ( $date_dues, $itemnumber, $difference ) = @_;
477 my $dateinsec = UnixDate( $date_dues, "%o" );
478 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
479 localtime($dateinsec);
480 my @result = GetWdayFromItemnumber($itemnumber);
484 for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
487 for ( $j = 0 ; $j < $difference ; $j++ ) {
488 if ( $result[$i]->{'weekday'} == $k ) {
489 push( @dayclosedcount, $k );
492 ( $k = 0 ) if ( $k eq 7 );
495 return scalar(@dayclosedcount);
499 =head2 GetWayFromItemnumber
501 &Getwdayfromitemnumber($itemnumber);
503 return the different week day from repeatable_holidays table
505 C<$itemnumber> is item number.
509 sub GetWdayFromItemnumber {
510 my ($itemnumber) = @_;
511 my $iteminfo = GetIssuesIteminfo($itemnumber);
513 my $query = qq|SELECT weekday
514 FROM repeatable_holidays
517 my $sth = C4::Context->dbh->prepare($query);
519 $sth->execute( $iteminfo->{'branchcode'} );
520 while ( my $weekday = $sth->fetchrow_hashref ) {
521 push( @result, $weekday );
527 =head2 GetIssuesIteminfo
529 &GetIssuesIteminfo($itemnumber);
531 return all data from issues about item
533 C<$itemnumber> is item number.
537 sub GetIssuesIteminfo {
538 my ($itemnumber) = @_;
539 my $dbh = C4::Context->dbh;
540 my $query = qq|SELECT *
544 my $sth = $dbh->prepare($query);
545 $sth->execute($itemnumber);
546 my ($issuesinfo) = $sth->fetchrow_hashref;
553 &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
555 (Note: the following is mostly conjecture and guesswork.)
557 Updates the fine owed on an overdue book.
559 C<$itemnumber> is the book's item number.
561 C<$borrowernumber> is the borrower number of the patron who currently
562 has the book on loan.
564 C<$amount> is the current amount owed by the patron.
566 C<$type> will be used in the description of the fine.
568 C<$description> is a string that must be present in the description of
569 the fine. I think this is expected to be a date in DD/MM/YYYY format.
571 C<&UpdateFine> looks up the amount currently owed on the given item
572 and sets it to C<$amount>, creating, if necessary, a new entry in the
573 accountlines table of the Koha database.
578 # Question: Why should the caller have to
579 # specify both the item number and the borrower number? A book can't
580 # be on loan to two different people, so the item number should be
583 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
586 my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
587 $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
588 my $dbh = C4::Context->dbh;
589 # FIXME - What exactly is this query supposed to do? It looks up an
590 # entry in accountlines that matches the given item and borrower
591 # numbers, where the description contains $due, and where the
592 # account type has one of several values, but what does this _mean_?
593 # Does it look up existing fines for this item?
594 # FIXME - What are these various account types? ("FU", "O", "F", "M")
596 # "A" is Account Management Fee
601 # "FU" is Fine UPDATE??
603 # "REF" is Cash Refund
604 my $sth = $dbh->prepare(
605 "SELECT * FROM accountlines
608 AND accounttype IN ('FU','O','F','M')
609 AND description like ? "
611 $sth->execute( $itemnum, $borrowernumber, "%$due%" );
613 if ( my $data = $sth->fetchrow_hashref ) {
615 # we're updating an existing fine. Only modify if we're adding to the charge.
616 # Note that in the current implementation, you cannot pay against an accruing fine
617 # (i.e. , of accounttype 'FU'). Doing so will break accrual.
618 if ( $data->{'amount'} != $amount ) {
619 my $diff = $amount - $data->{'amount'};
620 $diff = 0 if ( $data->{amount} > $amount);
621 my $out = $data->{'amountoutstanding'} + $diff;
624 SET date=now(), amount=?, amountoutstanding=?,
625 lastincrement=?, accounttype='FU'
626 WHERE borrowernumber=?
628 AND accounttype IN ('FU','O')
629 AND description LIKE ?
631 my $sth2 = $dbh->prepare($query);
632 # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
633 # LIMIT 1 added to prevent multiple affected lines
634 # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.
635 # But actually, we should just have a regular autoincrementing PK and forget accountline,
636 # including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
637 # FIXME: Why only 2 account types here?
638 $debug and print STDERR "UpdateFine query: $query\n" .
639 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
640 $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
642 # print "no update needed $data->{'amount'}"
645 my $sth4 = $dbh->prepare(
646 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
648 $sth4->execute($itemnum);
649 my $title = $sth4->fetchrow;
651 # # print "not in account";
652 # my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
655 # # FIXME - Make $accountno a scalar.
656 # my @accountno = $sth3->fetchrow_array;
660 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
661 my $desc = ($type ? "$type " : '') . "$title $due"; # FIXEDME, avoid whitespace prefix on empty $type
662 my $query = "INSERT INTO accountlines
663 (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
664 VALUES (?,?,now(),?,?,'FU',?,?,?)";
665 my $sth2 = $dbh->prepare($query);
666 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
667 $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
674 "due=".$due." amount=".$amount." itemnumber=".$itemnum
675 ) if C4::Context->preference("FinesLog");
680 $borrower = &BorType($borrowernumber);
682 Looks up a patron by borrower number.
684 C<$borrower> is a reference-to-hash whose keys are all of the fields
685 from the borrowers and categories tables of the Koha database. Thus,
686 C<$borrower> contains all information about both the borrower and
687 category he or she belongs to.
693 my ($borrowernumber) = @_;
694 my $dbh = C4::Context->dbh;
695 my $sth = $dbh->prepare(
696 "SELECT * from borrowers
697 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
698 WHERE borrowernumber=?"
700 $sth->execute($borrowernumber);
701 return $sth->fetchrow_hashref;
704 =head2 ReplacementCost
706 $cost = &ReplacementCost($itemnumber);
708 Returns the replacement cost of the item with the given item number.
713 sub ReplacementCost {
715 my $dbh = C4::Context->dbh;
717 $dbh->prepare("Select replacementprice from items where itemnumber=?");
718 $sth->execute($itemnum);
720 # FIXME - Use fetchrow_array or a slice.
721 my $data = $sth->fetchrow_hashref;
722 return ( $data->{'replacementprice'} );
727 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
729 return the total of fine
731 C<$itemnum> is item number
733 C<$borrowernumber> is the borrowernumber
739 my ( $itemnum, $borrowernumber ) = @_;
740 my $dbh = C4::Context->dbh();
741 my $query = "SELECT sum(amountoutstanding) FROM accountlines
742 where accounttype like 'F%'
743 AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
744 my $sth = $dbh->prepare($query);
745 $sth->execute( $itemnum, $borrowernumber );
746 my $data = $sth->fetchrow_hashref();
747 return ( $data->{'sum(amountoutstanding)'} );
751 =head2 GetIssuingRules
753 FIXME - This sub should be deprecated and removed.
754 It ignores branch and defaults.
756 $data = &GetIssuingRules($itemtype,$categorycode);
758 Looks up for all issuingrules an item info
760 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
761 from the borrowers and categories tables of the Koha database. Thus,
763 C<$categorycode> contains information about borrowers category
765 C<$data> contains all information about both the borrower and
766 category he or she belongs to.
769 sub GetIssuingRules {
770 warn "GetIssuingRules is deprecated: use GetIssuingRule from C4::Circulation instead.";
771 my ($itemtype,$categorycode)=@_;
772 my $dbh = C4::Context->dbh();
773 my $query=qq|SELECT *
775 WHERE issuingrules.itemtype=?
776 AND issuingrules.categorycode=?
778 my $sth = $dbh->prepare($query);
780 $sth->execute($itemtype,$categorycode);
781 return $sth->fetchrow_hashref;
785 sub ReplacementCost2 {
786 my ( $itemnum, $borrowernumber ) = @_;
787 my $dbh = C4::Context->dbh();
788 my $query = "SELECT amountoutstanding
790 WHERE accounttype like 'L'
791 AND amountoutstanding > 0
793 AND borrowernumber= ?";
794 my $sth = $dbh->prepare($query);
795 $sth->execute( $itemnum, $borrowernumber );
796 my $data = $sth->fetchrow_hashref();
797 return ( $data->{'amountoutstanding'} );
801 =head2 GetNextIdNotify
803 ($result) = &GetNextIdNotify($reference);
805 Returns the new file number
807 C<$result> contains the next file number
809 C<$reference> contains the beggining of file number
813 sub GetNextIdNotify {
814 my ($reference) = @_;
815 my $query = qq|SELECT max(notify_id)
817 WHERE notify_id like \"$reference%\"
820 # AND borrowernumber=?|;
821 my $dbh = C4::Context->dbh;
822 my $sth = $dbh->prepare($query);
824 my $result = $sth->fetchrow;
826 if ( $result eq '' ) {
827 ( $result = $reference . "01" );
830 $count = substr( $result, 6 ) + 1;
833 ( $count = "0" . $count );
835 $result = $reference . $count;
840 =head2 NumberNotifyId
842 (@notify) = &NumberNotifyId($borrowernumber);
844 Returns amount for all file per borrowers
845 C<@notify> array contains all file per borrowers
847 C<$notify_id> contains the file number for the borrower number nad item number
852 my ($borrowernumber)=@_;
853 my $dbh = C4::Context->dbh;
854 my $query=qq| SELECT distinct(notify_id)
856 WHERE borrowernumber=?|;
858 my $sth = $dbh->prepare($query);
859 $sth->execute($borrowernumber);
860 while ( my ($numberofnotify) = $sth->fetchrow ) {
861 push( @notify, $numberofnotify );
868 ($totalnotify) = &AmountNotify($notifyid);
870 Returns amount for all file per borrowers
871 C<$notifyid> is the file number
873 C<$totalnotify> contains amount of a file
875 C<$notify_id> contains the file number for the borrower number and item number
880 my ($notifyid,$borrowernumber)=@_;
881 my $dbh = C4::Context->dbh;
882 my $query=qq| SELECT sum(amountoutstanding)
884 WHERE notify_id=? AND borrowernumber = ?|;
885 my $sth=$dbh->prepare($query);
886 $sth->execute($notifyid,$borrowernumber);
887 my $totalnotify=$sth->fetchrow;
889 return ($totalnotify);
895 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
897 Returns the file number per borrower and itemnumber
899 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
900 from the items tables of the Koha database. Thus,
902 C<$itemnumber> contains the borrower categorycode
904 C<$notify_id> contains the file number for the borrower number nad item number
909 my ( $borrowernumber, $itemnumber ) = @_;
910 my $query = qq|SELECT notify_id
912 WHERE borrowernumber=?
914 AND (accounttype='FU' or accounttype='O')|;
915 my $dbh = C4::Context->dbh;
916 my $sth = $dbh->prepare($query);
917 $sth->execute( $borrowernumber, $itemnumber );
918 my ($notify_id) = $sth->fetchrow;
923 =head2 CreateItemAccountLine
925 () = &CreateItemAccountLine($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
927 update the account lines with file number or with file level
929 C<$items> is a reference-to-hash whose keys are all of the fields
930 from the items tables of the Koha database. Thus,
932 C<$itemnumber> contains the item number
934 C<$borrowernumber> contains the borrower number
936 C<$date> contains the date of the day
938 C<$amount> contains item price
940 C<$description> contains the descritpion of accounttype
942 C<$accounttype> contains the account type
944 C<$amountoutstanding> contains the $amountoutstanding
946 C<$timestamp> contains the timestamp with time and the date of the day
948 C<$notify_id> contains the file number
950 C<$level> contains the file level
954 sub CreateItemAccountLine {
956 $borrowernumber, $itemnumber, $date, $amount,
957 $description, $accounttype, $amountoutstanding, $timestamp,
960 my $dbh = C4::Context->dbh;
961 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
962 my $query = "INSERT into accountlines
963 (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
965 (?,?,?,?,?,?,?,?,?,?,?)";
967 my $sth = $dbh->prepare($query);
969 $borrowernumber, $nextaccntno, $itemnumber,
970 $date, $amount, $description,
971 $accounttype, $amountoutstanding, $timestamp,
976 =head2 UpdateAccountLines
978 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
980 update the account lines with file number or with file level
982 C<$items> is a reference-to-hash whose keys are all of the fields
983 from the items tables of the Koha database. Thus,
985 C<$itemnumber> contains the item number
987 C<$notify_id> contains the file number
989 C<$notify_level> contains the file level
991 C<$borrowernumber> contains the borrowernumber
995 sub UpdateAccountLines {
996 my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
998 if ( $notify_id eq '' ) {
999 $query = qq|UPDATE accountlines
1001 WHERE borrowernumber=? AND itemnumber=?
1002 AND (accounttype='FU' or accounttype='O')|;
1004 $query = qq|UPDATE accountlines
1005 SET notify_id=?, notify_level=?
1006 WHERE borrowernumber=?
1008 AND (accounttype='FU' or accounttype='O')|;
1011 my $sth = C4::Context->dbh->prepare($query);
1012 if ( $notify_id eq '' ) {
1013 $sth->execute( $notify_level, $borrowernumber, $itemnumber );
1015 $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
1021 ($items) = &GetItems($itemnumber);
1023 Returns the list of all delays from overduerules.
1025 C<$items> is a reference-to-hash whose keys are all of the fields
1026 from the items tables of the Koha database. Thus,
1028 C<$itemnumber> contains the borrower categorycode
1032 # FIXME: This is a bad function to have here.
1033 # Shouldn't it be in C4::Items?
1034 # Shouldn't it be called GetItem since you only get 1 row?
1035 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
1038 my $itemnumber = shift or return;
1039 my $query = qq|SELECT *
1041 WHERE itemnumber=?|;
1042 my $sth = C4::Context->dbh->prepare($query);
1043 $sth->execute($itemnumber);
1044 my ($items) = $sth->fetchrow_hashref;
1048 =head2 GetOverdueDelays
1050 (@delays) = &GetOverdueDelays($categorycode);
1052 Returns the list of all delays from overduerules.
1054 C<@delays> it's an array contains the three delays from overduerules table
1056 C<$categorycode> contains the borrower categorycode
1060 sub GetOverdueDelays {
1061 my ($category) = @_;
1062 my $query = qq|SELECT delay1,delay2,delay3
1064 WHERE categorycode=?|;
1065 my $sth = C4::Context->dbh->prepare($query);
1066 $sth->execute($category);
1067 my (@delays) = $sth->fetchrow_array;
1071 =head2 GetBranchcodesWithOverdueRules
1075 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
1077 returns a list of branch codes for branches with overdue rules defined.
1083 sub GetBranchcodesWithOverdueRules {
1084 my $dbh = C4::Context->dbh;
1085 my $rqoverduebranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode <> ''");
1086 my $availbranches = C4::Branch::GetBranches();
1088 $rqoverduebranches->execute;
1089 my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
1091 my $defaultbranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode = ''");
1092 $defaultbranches->execute();
1093 if($defaultbranches->rows > 0){
1094 foreach my $branch (keys %$availbranches){
1095 if(not grep{/^$branch$/} @branches){
1096 push @branches, $branch;
1103 =head2 CheckAccountLineLevelInfo
1105 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
1107 Check and Returns the list of all overdue books.
1109 C<$exist> contains number of line in accounlines
1110 with the same .biblionumber,itemnumber,accounttype,and notify_level
1112 C<$borrowernumber> contains the borrower number
1114 C<$itemnumber> contains item number
1116 C<$accounttype> contains account type
1118 C<$notify_level> contains the accountline level
1123 sub CheckAccountLineLevelInfo {
1124 my ( $borrowernumber, $itemnumber, $level ) = @_;
1125 my $dbh = C4::Context->dbh;
1126 my $query = qq|SELECT count(*)
1128 WHERE borrowernumber =?
1130 AND notify_level=?|;
1131 my $sth = $dbh->prepare($query);
1132 $sth->execute( $borrowernumber, $itemnumber, $level );
1133 my ($exist) = $sth->fetchrow;
1137 =head2 GetOverduerules
1139 ($overduerules) = &GetOverduerules($categorycode);
1141 Returns the value of borrowers (debarred or not) with notify level
1143 C<$overduerules> return value of debbraed field in overduerules table
1145 C<$category> contains the borrower categorycode
1147 C<$notify_level> contains the notify level
1151 sub GetOverduerules {
1152 my ( $category, $notify_level ) = @_;
1153 my $dbh = C4::Context->dbh;
1154 my $query = qq|SELECT debarred$notify_level
1156 WHERE categorycode=?|;
1157 my $sth = $dbh->prepare($query);
1158 $sth->execute($category);
1159 my ($overduerules) = $sth->fetchrow;
1160 return ($overduerules);
1164 =head2 CheckBorrowerDebarred
1166 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1168 Check if the borrowers is already debarred
1170 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1172 C<$borrowernumber> contains the borrower number
1176 # FIXME: Shouldn't this be in C4::Members?
1177 sub CheckBorrowerDebarred {
1178 my ($borrowernumber) = @_;
1179 my $dbh = C4::Context->dbh;
1183 WHERE borrowernumber=?
1185 my $sth = $dbh->prepare($query);
1186 $sth->execute($borrowernumber);
1187 my ($debarredstatus) = $sth->fetchrow;
1188 return ( $debarredstatus eq '1' ? 1 : 0 );
1191 =head2 UpdateBorrowerDebarred
1193 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
1195 update status of borrowers in borrowers table (field debarred)
1197 C<$borrowernumber> borrower number
1201 sub UpdateBorrowerDebarred{
1202 my($borrowernumber) = @_;
1203 my $dbh = C4::Context->dbh;
1204 my $query=qq|UPDATE borrowers
1206 WHERE borrowernumber=?
1208 my $sth=$dbh->prepare($query);
1209 $sth->execute($borrowernumber);
1214 =head2 CheckExistantNotifyid
1216 ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1218 Check and Returns the notify id if exist else return 0.
1220 C<$exist> contains a notify_id
1222 C<$borrowernumber> contains the borrower number
1224 C<$date_due> contains the date of item return
1229 sub CheckExistantNotifyid {
1230 my ( $borrowernumber, $date_due ) = @_;
1231 my $dbh = C4::Context->dbh;
1232 my $query = qq|SELECT notify_id FROM accountlines
1233 LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1234 WHERE accountlines.borrowernumber =?
1236 my $sth = $dbh->prepare($query);
1237 $sth->execute( $borrowernumber, $date_due );
1238 return $sth->fetchrow || 0;
1241 =head2 CheckAccountLineItemInfo
1243 ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1245 Check and Returns the list of all overdue items from the same file number(notify_id).
1247 C<$exist> contains number of line in accounlines
1248 with the same .biblionumber,itemnumber,accounttype,notify_id
1250 C<$borrowernumber> contains the borrower number
1252 C<$itemnumber> contains item number
1254 C<$accounttype> contains account type
1256 C<$notify_id> contains the file number
1260 sub CheckAccountLineItemInfo {
1261 my ( $borrowernumber, $itemnumber, $accounttype, $notify_id ) = @_;
1262 my $dbh = C4::Context->dbh;
1263 my $query = qq|SELECT count(*) FROM accountlines
1264 WHERE borrowernumber =?
1268 my $sth = $dbh->prepare($query);
1269 $sth->execute( $borrowernumber, $itemnumber, $accounttype, $notify_id );
1270 my ($exist) = $sth->fetchrow;
1274 =head2 CheckItemNotify
1276 Sql request to check if the document has alreday been notified
1277 this function is not exported, only used with GetOverduesForBranch
1281 sub CheckItemNotify {
1282 my ($notify_id,$notify_level,$itemnumber) = @_;
1283 my $dbh = C4::Context->dbh;
1284 my $sth = $dbh->prepare("
1288 AND notify_level = ?
1289 AND itemnumber = ? ");
1290 $sth->execute($notify_id,$notify_level,$itemnumber);
1291 my $notified = $sth->fetchrow;
1295 =head2 GetOverduesForBranch
1297 Sql request for display all information for branchoverdues.pl
1298 2 possibilities : with or without location .
1299 display is filtered by branch
1301 FIXME: This function should be renamed.
1305 sub GetOverduesForBranch {
1306 my ( $branch, $location) = @_;
1307 my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype ";
1308 my $dbh = C4::Context->dbh;
1311 borrowers.borrowernumber,
1313 borrowers.firstname,
1317 biblio.biblionumber,
1321 branches.branchname,
1323 items.itemcallnumber,
1326 itemtypes.description,
1327 accountlines.notify_id,
1328 accountlines.notify_level,
1329 accountlines.amountoutstanding
1331 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber
1332 AND issues.borrowernumber = accountlines.borrowernumber
1333 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1334 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1335 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1336 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1337 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1338 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1339 WHERE (accountlines.amountoutstanding != '0.000000')
1340 AND (accountlines.accounttype = 'FU' )
1341 AND (issues.branchcode = ? )
1342 AND (issues.date_due <= NOW())
1348 $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1349 $sth->execute($branch, $location);
1351 $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1352 $sth->execute($branch);
1354 while ( my $data = $sth->fetchrow_hashref ) {
1355 #check if the document has already been notified
1356 my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1357 if ($countnotify eq '0') {
1358 $getoverdues[$i] = $data;
1362 return (@getoverdues);
1366 =head2 AddNotifyLine
1368 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1370 Creat a line into notify, if the method is phone, the notification_send_date is implemented to
1375 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1376 my $dbh = C4::Context->dbh;
1377 if ( $method eq "phone" ) {
1378 my $sth = $dbh->prepare(
1379 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1380 VALUES (?,?,now(),now(),?,?,?)"
1382 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1386 my $sth = $dbh->prepare(
1387 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1388 VALUES (?,?,now(),?,?,?)"
1390 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1396 =head2 RemoveNotifyLine
1398 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1400 Cancel a notification
1404 sub RemoveNotifyLine {
1405 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1406 my $dbh = C4::Context->dbh;
1407 my $sth = $dbh->prepare(
1408 "DELETE FROM notifys
1414 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1423 Koha Developement team <info@koha.org>