4 # Copyright 2000-2002 Katipo Communications
5 # copyright 2010 BibLibre
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #use warnings; FIXME - Bug 2505
24 use Date::Calc qw/Today Date_to_Days/;
25 use Date::Manip qw/UnixDate/;
29 use C4::Log; # logaction
32 use vars qw($VERSION @ISA @EXPORT);
35 # set the version for version checking
39 # subs to rename (and maybe merge some...)
44 &CheckAccountLineLevelInfo
45 &CheckAccountLineItemInfo
46 &CheckExistantNotifyid
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 < CURDATE()
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 < CURDATE()
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({});
160 ($count, $overdueitems) = checkoverdues($borrowernumber);
162 Returns a count and a list of overdueitems for a given borrowernumber
167 my $borrowernumber = shift or return;
168 my $sth = C4::Context->dbh->prepare(
169 "SELECT * FROM issues
170 LEFT JOIN items ON issues.itemnumber = items.itemnumber
171 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
172 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
173 WHERE issues.borrowernumber = ?
174 AND issues.date_due < CURDATE()"
176 # FIXME: SELECT * across 4 tables? do we really need the marc AND marcxml blobs??
177 $sth->execute($borrowernumber);
178 my $results = $sth->fetchall_arrayref({});
179 return ( scalar(@$results), $results); # returning the count and the results is silly
184 ($amount, $chargename, $daycount, $daycounttotal) = &CalcFine($item,
185 $categorycode, $branch, $days_overdue,
186 $description, $start_date, $end_date );
188 Calculates the fine for a book.
190 The issuingrules table in the Koha database is a fine matrix, listing
191 the penalties for each type of patron for each type of item and each branch (e.g., the
192 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
193 members might get a longer grace period between the first and second
194 reminders that a book is overdue).
197 C<$item> is an item object (hashref).
199 C<$categorycode> is the category code (string) of the patron who currently has
202 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
204 C<$days_overdue> is the number of days elapsed since the book's due date.
205 NOTE: supplying days_overdue is deprecated.
207 C<$start_date> & C<$end_date> are C4::Dates objects
208 defining the date range over which to determine the fine.
209 Note that if these are defined, we ignore C<$difference> and C<$dues> ,
210 but retain these for backwards-comptibility with extant fines scripts.
212 Fines scripts should just supply the date range over which to calculate the fine.
214 C<&CalcFine> returns four values:
216 C<$amount> is the fine owed by the patron (see above).
218 C<$chargename> is the chargename field from the applicable record in
219 the categoryitem table, whatever that is.
221 C<$daycount> is the number of days between start and end dates, Calendar adjusted (where needed),
222 minus any applicable grace period.
224 C<$daycounttotal> is C<$daycount> without consideration of grace period.
226 FIXME - What is chargename supposed to be ?
228 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
229 or "Final Notice". But CalcFine never defined any value.
234 my ( $item, $bortype, $branchcode, $difference ,$dues , $start_date, $end_date ) = @_;
235 $debug and warn sprintf("CalcFine(%s, %s, %s, %s, %s, %s, %s)",
236 ($item ? '{item}' : 'UNDEF'),
237 ($bortype || 'UNDEF'),
238 ($branchcode || 'UNDEF'),
239 ($difference || 'UNDEF'),
241 ($start_date ? ($start_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF'),
242 ( $end_date ? ( $end_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF')
244 my $dbh = C4::Context->dbh;
247 # get issuingrules (fines part will be used)
248 $debug and warn sprintf("CalcFine calling GetIssuingRule(%s, %s, %s)", $bortype, $item->{'itemtype'}, $branchcode);
249 my $data = C4::Circulation::GetIssuingRule($bortype, $item->{'itemtype'}, $branchcode);
251 # if $difference is supplied, the difference has already been calculated, but we still need to adjust for the calendar.
252 # use copy-pasted functions from calendar module. (deprecated -- these functions will be removed from C4::Overdues ).
253 my $countspecialday = &GetSpecialHolidays($dues,$item->{itemnumber});
254 my $countrepeatableday = &GetRepeatableHolidays($dues,$item->{itemnumber},$difference);
255 my $countalldayclosed = $countspecialday + $countrepeatableday;
256 $daystocharge = $difference - $countalldayclosed;
258 # if $difference is not supplied, we have C4::Dates objects giving us the date range, and we use the calendar module.
259 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
260 my $calendar = C4::Calendar->new( branchcode => $branchcode );
261 $daystocharge = $calendar->daysBetween( $start_date, $end_date );
263 $daystocharge = Date_to_Days(split('-',$end_date->output('iso'))) - Date_to_Days(split('-',$start_date->output('iso')));
266 # correct for grace period.
267 my $days_minus_grace = $daystocharge - $data->{'firstremind'};
268 if ($data->{'chargeperiod'} > 0 && $days_minus_grace > 0 ) {
269 $amount = int($daystocharge / $data->{'chargeperiod'}) * $data->{'fine'};
271 # a zero (or null) chargeperiod means no charge.
273 $amount = C4::Context->preference('maxFine') if(C4::Context->preference('maxFine') && ( $amount > C4::Context->preference('maxFine')));
274 $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
275 return ($amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
276 # FIXME: chargename is NEVER populated anywhere.
280 =head2 GetSpecialHolidays
282 &GetSpecialHolidays($date_dues,$itemnumber);
284 return number of special days between date of the day and date due
286 C<$date_dues> is the envisaged date of book return.
288 C<$itemnumber> is the book's item number.
292 sub GetSpecialHolidays {
293 my ( $date_dues, $itemnumber ) = @_;
295 # calcul the today date
296 my $today = join "-", &Today();
298 # return the holdingbranch
299 my $iteminfo = GetIssuesIteminfo($itemnumber);
301 # use sql request to find all date between date_due and today
302 my $dbh = C4::Context->dbh;
304 qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
305 FROM `special_holidays`
306 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
307 AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
310 my @result = GetWdayFromItemnumber($itemnumber);
314 my $sth = $dbh->prepare($query);
315 $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
316 ; # FIXME: just use NOW() in SQL instead of passing in $today
318 while ( my $special_date = $sth->fetchrow_hashref ) {
319 push( @result_date, $special_date );
322 my $specialdaycount = scalar(@result_date);
324 for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
325 $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
326 ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
327 localtime($dateinsec);
328 for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
329 if ( $wday == ( $result[$j]->{'weekday'} ) ) {
335 return $specialdaycount;
338 =head2 GetRepeatableHolidays
340 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
342 return number of day closed between date of the day and date due
344 C<$date_dues> is the envisaged date of book return.
346 C<$itemnumber> is item number.
348 C<$difference> numbers of between day date of the day and date due
352 sub GetRepeatableHolidays {
353 my ( $date_dues, $itemnumber, $difference ) = @_;
354 my $dateinsec = UnixDate( $date_dues, "%o" );
355 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
356 localtime($dateinsec);
357 my @result = GetWdayFromItemnumber($itemnumber);
361 for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
364 for ( $j = 0 ; $j < $difference ; $j++ ) {
365 if ( $result[$i]->{'weekday'} == $k ) {
366 push( @dayclosedcount, $k );
369 ( $k = 0 ) if ( $k eq 7 );
372 return scalar(@dayclosedcount);
376 =head2 GetWayFromItemnumber
378 &Getwdayfromitemnumber($itemnumber);
380 return the different week day from repeatable_holidays table
382 C<$itemnumber> is item number.
386 sub GetWdayFromItemnumber {
387 my ($itemnumber) = @_;
388 my $iteminfo = GetIssuesIteminfo($itemnumber);
390 my $query = qq|SELECT weekday
391 FROM repeatable_holidays
394 my $sth = C4::Context->dbh->prepare($query);
396 $sth->execute( $iteminfo->{'branchcode'} );
397 while ( my $weekday = $sth->fetchrow_hashref ) {
398 push( @result, $weekday );
404 =head2 GetIssuesIteminfo
406 &GetIssuesIteminfo($itemnumber);
408 return all data from issues about item
410 C<$itemnumber> is item number.
414 sub GetIssuesIteminfo {
415 my ($itemnumber) = @_;
416 my $dbh = C4::Context->dbh;
417 my $query = qq|SELECT *
421 my $sth = $dbh->prepare($query);
422 $sth->execute($itemnumber);
423 my ($issuesinfo) = $sth->fetchrow_hashref;
430 &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
432 (Note: the following is mostly conjecture and guesswork.)
434 Updates the fine owed on an overdue book.
436 C<$itemnumber> is the book's item number.
438 C<$borrowernumber> is the borrower number of the patron who currently
439 has the book on loan.
441 C<$amount> is the current amount owed by the patron.
443 C<$type> will be used in the description of the fine.
445 C<$description> is a string that must be present in the description of
446 the fine. I think this is expected to be a date in DD/MM/YYYY format.
448 C<&UpdateFine> looks up the amount currently owed on the given item
449 and sets it to C<$amount>, creating, if necessary, a new entry in the
450 accountlines table of the Koha database.
455 # Question: Why should the caller have to
456 # specify both the item number and the borrower number? A book can't
457 # be on loan to two different people, so the item number should be
460 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
463 my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
464 $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
465 my $dbh = C4::Context->dbh;
466 # FIXME - What exactly is this query supposed to do? It looks up an
467 # entry in accountlines that matches the given item and borrower
468 # numbers, where the description contains $due, and where the
469 # account type has one of several values, but what does this _mean_?
470 # Does it look up existing fines for this item?
471 # FIXME - What are these various account types? ("FU", "O", "F", "M")
473 # "A" is Account Management Fee
478 # "FU" is Fine UPDATE??
480 # "REF" is Cash Refund
481 my $sth = $dbh->prepare(
482 "SELECT * FROM accountlines
485 AND accounttype IN ('FU','O','F','M')
486 AND description like ? "
488 $sth->execute( $itemnum, $borrowernumber, "%$due%" );
490 if ( my $data = $sth->fetchrow_hashref ) {
492 # we're updating an existing fine. Only modify if amount changed
493 # Note that in the current implementation, you cannot pay against an accruing fine
494 # (i.e. , of accounttype 'FU'). Doing so will break accrual.
495 if ( $data->{'amount'} != $amount ) {
496 my $diff = $amount - $data->{'amount'};
497 #3341: diff could be positive or negative!
498 my $out = $data->{'amountoutstanding'} + $diff;
501 SET date=now(), amount=?, amountoutstanding=?,
502 lastincrement=?, accounttype='FU'
503 WHERE borrowernumber=?
505 AND accounttype IN ('FU','O')
506 AND description LIKE ?
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%");
519 # print "no update needed $data->{'amount'}"
522 my $sth4 = $dbh->prepare(
523 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
525 $sth4->execute($itemnum);
526 my $title = $sth4->fetchrow;
528 # # print "not in account";
529 # my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
532 # # FIXME - Make $accountno a scalar.
533 # my @accountno = $sth3->fetchrow_array;
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);
551 "due=".$due." amount=".$amount." itemnumber=".$itemnum
552 ) if C4::Context->preference("FinesLog");
557 $borrower = &BorType($borrowernumber);
559 Looks up a patron by borrower number.
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.
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=?"
577 $sth->execute($borrowernumber);
578 return $sth->fetchrow_hashref;
581 =head2 ReplacementCost
583 $cost = &ReplacementCost($itemnumber);
585 Returns the replacement cost of the item with the given item number.
590 sub ReplacementCost {
592 my $dbh = C4::Context->dbh;
594 $dbh->prepare("Select replacementprice from items where itemnumber=?");
595 $sth->execute($itemnum);
597 # FIXME - Use fetchrow_array or a slice.
598 my $data = $sth->fetchrow_hashref;
599 return ( $data->{'replacementprice'} );
604 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
606 return the total of fine
608 C<$itemnum> is item number
610 C<$borrowernumber> is the borrowernumber
616 my ( $itemnum, $borrowernumber ) = @_;
617 my $dbh = C4::Context->dbh();
618 my $query = "SELECT sum(amountoutstanding) FROM accountlines
619 where accounttype like 'F%'
620 AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
621 my $sth = $dbh->prepare($query);
622 $sth->execute( $itemnum, $borrowernumber );
623 my $data = $sth->fetchrow_hashref();
624 return ( $data->{'sum(amountoutstanding)'} );
628 =head2 GetIssuingRules
630 FIXME - This sub should be deprecated and removed.
631 It ignores branch and defaults.
633 $data = &GetIssuingRules($itemtype,$categorycode);
635 Looks up for all issuingrules an item info
637 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
638 from the borrowers and categories tables of the Koha database. Thus,
640 C<$categorycode> contains information about borrowers category
642 C<$data> contains all information about both the borrower and
643 category he or she belongs to.
646 sub GetIssuingRules {
647 warn "GetIssuingRules is deprecated: use GetIssuingRule from C4::Circulation instead.";
648 my ($itemtype,$categorycode)=@_;
649 my $dbh = C4::Context->dbh();
650 my $query=qq|SELECT *
652 WHERE issuingrules.itemtype=?
653 AND issuingrules.categorycode=?
655 my $sth = $dbh->prepare($query);
657 $sth->execute($itemtype,$categorycode);
658 return $sth->fetchrow_hashref;
662 sub ReplacementCost2 {
663 my ( $itemnum, $borrowernumber ) = @_;
664 my $dbh = C4::Context->dbh();
665 my $query = "SELECT amountoutstanding
667 WHERE accounttype like 'L'
668 AND amountoutstanding > 0
670 AND borrowernumber= ?";
671 my $sth = $dbh->prepare($query);
672 $sth->execute( $itemnum, $borrowernumber );
673 my $data = $sth->fetchrow_hashref();
674 return ( $data->{'amountoutstanding'} );
678 =head2 GetNextIdNotify
680 ($result) = &GetNextIdNotify($reference);
682 Returns the new file number
684 C<$result> contains the next file number
686 C<$reference> contains the beggining of file number
690 sub GetNextIdNotify {
691 my ($reference) = @_;
692 my $query = qq|SELECT max(notify_id)
694 WHERE notify_id like \"$reference%\"
697 # AND borrowernumber=?|;
698 my $dbh = C4::Context->dbh;
699 my $sth = $dbh->prepare($query);
701 my $result = $sth->fetchrow;
703 if ( $result eq '' ) {
704 ( $result = $reference . "01" );
707 $count = substr( $result, 6 ) + 1;
710 ( $count = "0" . $count );
712 $result = $reference . $count;
717 =head2 NumberNotifyId
719 (@notify) = &NumberNotifyId($borrowernumber);
721 Returns amount for all file per borrowers
722 C<@notify> array contains all file per borrowers
724 C<$notify_id> contains the file number for the borrower number nad item number
729 my ($borrowernumber)=@_;
730 my $dbh = C4::Context->dbh;
731 my $query=qq| SELECT distinct(notify_id)
733 WHERE borrowernumber=?|;
735 my $sth = $dbh->prepare($query);
736 $sth->execute($borrowernumber);
737 while ( my ($numberofnotify) = $sth->fetchrow ) {
738 push( @notify, $numberofnotify );
745 ($totalnotify) = &AmountNotify($notifyid);
747 Returns amount for all file per borrowers
748 C<$notifyid> is the file number
750 C<$totalnotify> contains amount of a file
752 C<$notify_id> contains the file number for the borrower number and item number
757 my ($notifyid,$borrowernumber)=@_;
758 my $dbh = C4::Context->dbh;
759 my $query=qq| SELECT sum(amountoutstanding)
761 WHERE notify_id=? AND borrowernumber = ?|;
762 my $sth=$dbh->prepare($query);
763 $sth->execute($notifyid,$borrowernumber);
764 my $totalnotify=$sth->fetchrow;
766 return ($totalnotify);
772 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
774 Returns the file number per borrower and itemnumber
776 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
777 from the items tables of the Koha database. Thus,
779 C<$itemnumber> contains the borrower categorycode
781 C<$notify_id> contains the file number for the borrower number nad item number
786 my ( $borrowernumber, $itemnumber ) = @_;
787 my $query = qq|SELECT notify_id
789 WHERE borrowernumber=?
791 AND (accounttype='FU' or accounttype='O')|;
792 my $dbh = C4::Context->dbh;
793 my $sth = $dbh->prepare($query);
794 $sth->execute( $borrowernumber, $itemnumber );
795 my ($notify_id) = $sth->fetchrow;
800 =head2 CreateItemAccountLine
802 () = &CreateItemAccountLine($borrowernumber, $itemnumber, $date, $amount,
803 $description, $accounttype, $amountoutstanding,
804 $timestamp, $notify_id, $level);
806 update the account lines with file number or with file level
808 C<$items> is a reference-to-hash whose keys are all of the fields
809 from the items tables of the Koha database. Thus,
811 C<$itemnumber> contains the item number
813 C<$borrowernumber> contains the borrower number
815 C<$date> contains the date of the day
817 C<$amount> contains item price
819 C<$description> contains the descritpion of accounttype
821 C<$accounttype> contains the account type
823 C<$amountoutstanding> contains the $amountoutstanding
825 C<$timestamp> contains the timestamp with time and the date of the day
827 C<$notify_id> contains the file number
829 C<$level> contains the file level
833 sub CreateItemAccountLine {
835 $borrowernumber, $itemnumber, $date, $amount,
836 $description, $accounttype, $amountoutstanding, $timestamp,
839 my $dbh = C4::Context->dbh;
840 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
841 my $query = "INSERT into accountlines
842 (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
844 (?,?,?,?,?,?,?,?,?,?,?)";
846 my $sth = $dbh->prepare($query);
848 $borrowernumber, $nextaccntno, $itemnumber,
849 $date, $amount, $description,
850 $accounttype, $amountoutstanding, $timestamp,
855 =head2 UpdateAccountLines
857 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
859 update the account lines with file number or with file level
861 C<$items> is a reference-to-hash whose keys are all of the fields
862 from the items tables of the Koha database. Thus,
864 C<$itemnumber> contains the item number
866 C<$notify_id> contains the file number
868 C<$notify_level> contains the file level
870 C<$borrowernumber> contains the borrowernumber
874 sub UpdateAccountLines {
875 my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
877 if ( $notify_id eq '' ) {
878 $query = qq|UPDATE accountlines
880 WHERE borrowernumber=? AND itemnumber=?
881 AND (accounttype='FU' or accounttype='O')|;
883 $query = qq|UPDATE accountlines
884 SET notify_id=?, notify_level=?
885 WHERE borrowernumber=?
887 AND (accounttype='FU' or accounttype='O')|;
890 my $sth = C4::Context->dbh->prepare($query);
891 if ( $notify_id eq '' ) {
892 $sth->execute( $notify_level, $borrowernumber, $itemnumber );
894 $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
900 ($items) = &GetItems($itemnumber);
902 Returns the list of all delays from overduerules.
904 C<$items> is a reference-to-hash whose keys are all of the fields
905 from the items tables of the Koha database. Thus,
907 C<$itemnumber> contains the borrower categorycode
911 # FIXME: This is a bad function to have here.
912 # Shouldn't it be in C4::Items?
913 # Shouldn't it be called GetItem since you only get 1 row?
914 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
917 my $itemnumber = shift or return;
918 my $query = qq|SELECT *
921 my $sth = C4::Context->dbh->prepare($query);
922 $sth->execute($itemnumber);
923 my ($items) = $sth->fetchrow_hashref;
927 =head2 GetOverdueDelays
929 (@delays) = &GetOverdueDelays($categorycode);
931 Returns the list of all delays from overduerules.
933 C<@delays> it's an array contains the three delays from overduerules table
935 C<$categorycode> contains the borrower categorycode
939 sub GetOverdueDelays {
941 my $query = qq|SELECT delay1,delay2,delay3
943 WHERE categorycode=?|;
944 my $sth = C4::Context->dbh->prepare($query);
945 $sth->execute($category);
946 my (@delays) = $sth->fetchrow_array;
950 =head2 GetBranchcodesWithOverdueRules
952 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
954 returns a list of branch codes for branches with overdue rules defined.
958 sub GetBranchcodesWithOverdueRules {
959 my $dbh = C4::Context->dbh;
960 my $rqoverduebranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode <> '' ORDER BY branchcode");
961 $rqoverduebranches->execute;
962 my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
964 my $availbranches = C4::Branch::GetBranches();
965 @branches = keys %$availbranches;
970 =head2 CheckAccountLineLevelInfo
972 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
974 Check and Returns the list of all overdue books.
976 C<$exist> contains number of line in accounlines
977 with the same .biblionumber,itemnumber,accounttype,and notify_level
979 C<$borrowernumber> contains the borrower number
981 C<$itemnumber> contains item number
983 C<$accounttype> contains account type
985 C<$notify_level> contains the accountline level
990 sub CheckAccountLineLevelInfo {
991 my ( $borrowernumber, $itemnumber, $level ) = @_;
992 my $dbh = C4::Context->dbh;
993 my $query = qq|SELECT count(*)
995 WHERE borrowernumber =?
998 my $sth = $dbh->prepare($query);
999 $sth->execute( $borrowernumber, $itemnumber, $level );
1000 my ($exist) = $sth->fetchrow;
1004 =head2 GetOverduerules
1006 ($overduerules) = &GetOverduerules($categorycode);
1008 Returns the value of borrowers (debarred or not) with notify level
1010 C<$overduerules> return value of debbraed field in overduerules table
1012 C<$category> contains the borrower categorycode
1014 C<$notify_level> contains the notify level
1018 sub GetOverduerules {
1019 my ( $category, $notify_level ) = @_;
1020 my $dbh = C4::Context->dbh;
1021 my $query = qq|SELECT debarred$notify_level
1023 WHERE categorycode=?|;
1024 my $sth = $dbh->prepare($query);
1025 $sth->execute($category);
1026 my ($overduerules) = $sth->fetchrow;
1027 return ($overduerules);
1031 =head2 CheckBorrowerDebarred
1033 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1035 Check if the borrowers is already debarred
1037 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1039 C<$borrowernumber> contains the borrower number
1043 # FIXME: Shouldn't this be in C4::Members?
1044 sub CheckBorrowerDebarred {
1045 my ($borrowernumber) = @_;
1046 my $dbh = C4::Context->dbh;
1050 WHERE borrowernumber=?
1052 my $sth = $dbh->prepare($query);
1053 $sth->execute($borrowernumber);
1054 my ($debarredstatus) = $sth->fetchrow;
1055 return ( $debarredstatus eq '1' ? 1 : 0 );
1058 =head2 UpdateBorrowerDebarred
1060 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
1062 update status of borrowers in borrowers table (field debarred)
1064 C<$borrowernumber> borrower number
1068 sub UpdateBorrowerDebarred{
1069 my($borrowernumber) = @_;
1070 my $dbh = C4::Context->dbh;
1071 my $query=qq|UPDATE borrowers
1073 WHERE borrowernumber=?
1075 my $sth=$dbh->prepare($query);
1076 $sth->execute($borrowernumber);
1081 =head2 CheckExistantNotifyid
1083 ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1085 Check and Returns the notify id if exist else return 0.
1087 C<$exist> contains a notify_id
1089 C<$borrowernumber> contains the borrower number
1091 C<$date_due> contains the date of item return
1096 sub CheckExistantNotifyid {
1097 my ( $borrowernumber, $date_due ) = @_;
1098 my $dbh = C4::Context->dbh;
1099 my $query = qq|SELECT notify_id FROM accountlines
1100 LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1101 WHERE accountlines.borrowernumber =?
1103 my $sth = $dbh->prepare($query);
1104 $sth->execute( $borrowernumber, $date_due );
1105 return $sth->fetchrow || 0;
1108 =head2 CheckAccountLineItemInfo
1110 ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1112 Check and Returns the list of all overdue items from the same file number(notify_id).
1114 C<$exist> contains number of line in accounlines
1115 with the same .biblionumber,itemnumber,accounttype,notify_id
1117 C<$borrowernumber> contains the borrower number
1119 C<$itemnumber> contains item number
1121 C<$accounttype> contains account type
1123 C<$notify_id> contains the file number
1127 sub CheckAccountLineItemInfo {
1128 my ( $borrowernumber, $itemnumber, $accounttype, $notify_id ) = @_;
1129 my $dbh = C4::Context->dbh;
1130 my $query = qq|SELECT count(*) FROM accountlines
1131 WHERE borrowernumber =?
1135 my $sth = $dbh->prepare($query);
1136 $sth->execute( $borrowernumber, $itemnumber, $accounttype, $notify_id );
1137 my ($exist) = $sth->fetchrow;
1141 =head2 CheckItemNotify
1143 Sql request to check if the document has alreday been notified
1144 this function is not exported, only used with GetOverduesForBranch
1148 sub CheckItemNotify {
1149 my ($notify_id,$notify_level,$itemnumber) = @_;
1150 my $dbh = C4::Context->dbh;
1151 my $sth = $dbh->prepare("
1155 AND notify_level = ?
1156 AND itemnumber = ? ");
1157 $sth->execute($notify_id,$notify_level,$itemnumber);
1158 my $notified = $sth->fetchrow;
1162 =head2 GetOverduesForBranch
1164 Sql request for display all information for branchoverdues.pl
1165 2 possibilities : with or without location .
1166 display is filtered by branch
1168 FIXME: This function should be renamed.
1172 sub GetOverduesForBranch {
1173 my ( $branch, $location) = @_;
1174 my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype ";
1175 my $dbh = C4::Context->dbh;
1178 borrowers.borrowernumber,
1180 borrowers.firstname,
1185 biblio.biblionumber,
1189 branches.branchname,
1192 items.itemcallnumber,
1195 itemtypes.description,
1196 accountlines.notify_id,
1197 accountlines.notify_level,
1198 accountlines.amountoutstanding
1200 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber
1201 AND issues.borrowernumber = accountlines.borrowernumber
1202 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1203 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1204 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1205 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1206 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1207 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1208 WHERE (accountlines.amountoutstanding != '0.000000')
1209 AND (accountlines.accounttype = 'FU' )
1210 AND (issues.branchcode = ? )
1211 AND (issues.date_due < CURDATE())
1217 $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1218 $sth->execute($branch, $location);
1220 $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1221 $sth->execute($branch);
1223 while ( my $data = $sth->fetchrow_hashref ) {
1224 #check if the document has already been notified
1225 my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1226 if ($countnotify eq '0') {
1227 $getoverdues[$i] = $data;
1231 return (@getoverdues);
1235 =head2 AddNotifyLine
1237 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1239 Create a line into notify, if the method is phone, the notification_send_date is implemented to
1244 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1245 my $dbh = C4::Context->dbh;
1246 if ( $method eq "phone" ) {
1247 my $sth = $dbh->prepare(
1248 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1249 VALUES (?,?,now(),now(),?,?,?)"
1251 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1255 my $sth = $dbh->prepare(
1256 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1257 VALUES (?,?,now(),?,?,?)"
1259 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1265 =head2 RemoveNotifyLine
1267 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1269 Cancel a notification
1273 sub RemoveNotifyLine {
1274 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1275 my $dbh = C4::Context->dbh;
1276 my $sth = $dbh->prepare(
1277 "DELETE FROM notifys
1283 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1292 Koha Development Team <http://koha-community.org/>