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
36 $VERSION = 3.07.00.049;
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
75 # subs to move to Members.pm
77 &CheckBorrowerDebarred
79 # subs to move to Biblio.pm
88 C4::Circulation::Fines - Koha module dealing with fines
96 This module contains several functions for dealing with fines for
97 overdue items. It is primarily used by the 'misc/fines2.pl' script.
103 $overdues = Getoverdues( { minimumdays => 1, maximumdays => 30 } );
105 Returns the list of all overdue books, with their itemtype.
107 C<$overdues> is a reference-to-array. Each element is a
108 reference-to-hash whose keys are the fields of the issues table in the
116 my $dbh = C4::Context->dbh;
118 if ( C4::Context->preference('item-level_itypes') ) {
120 SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode
122 LEFT JOIN items USING (itemnumber)
123 WHERE date_due < NOW()
127 SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode
129 LEFT JOIN items USING (itemnumber)
130 LEFT JOIN biblioitems USING (biblioitemnumber)
131 WHERE date_due < NOW()
136 if ( exists $params->{'minimumdays'} and exists $params->{'maximumdays'} ) {
137 $statement .= ' AND TO_DAYS( NOW() )-TO_DAYS( date_due ) BETWEEN ? and ? ';
138 push @bind_parameters, $params->{'minimumdays'}, $params->{'maximumdays'};
139 } elsif ( exists $params->{'minimumdays'} ) {
140 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) > ? ';
141 push @bind_parameters, $params->{'minimumdays'};
142 } elsif ( exists $params->{'maximumdays'} ) {
143 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ? ';
144 push @bind_parameters, $params->{'maximumdays'};
146 $statement .= 'ORDER BY borrowernumber';
147 my $sth = $dbh->prepare( $statement );
148 $sth->execute( @bind_parameters );
149 return $sth->fetchall_arrayref({});
155 ($count, $overdueitems) = checkoverdues($borrowernumber);
157 Returns a count and a list of overdueitems for a given borrowernumber
162 my $borrowernumber = shift or return;
163 # don't select biblioitems.marc or biblioitems.marcxml... too slow on large systems
164 my $sth = C4::Context->dbh->prepare(
165 "SELECT biblio.*, items.*, issues.*,
168 biblioitems.itemtype,
171 biblioitems.publicationyear,
172 biblioitems.publishercode,
173 biblioitems.volumedate,
174 biblioitems.volumedesc,
175 biblioitems.collectiontitle,
176 biblioitems.collectionissn,
177 biblioitems.collectionvolume,
178 biblioitems.editionstatement,
179 biblioitems.editionresponsibility,
187 biblioitems.cn_source,
188 biblioitems.cn_class,
190 biblioitems.cn_suffix,
192 biblioitems.totalissues
194 LEFT JOIN items ON issues.itemnumber = items.itemnumber
195 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
196 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
197 WHERE issues.borrowernumber = ?
198 AND issues.date_due < NOW()"
200 # FIXME: SELECT * across 4 tables? do we really need the marc AND marcxml blobs??
201 $sth->execute($borrowernumber);
202 my $results = $sth->fetchall_arrayref({});
203 return ( scalar(@$results), $results); # returning the count and the results is silly
208 ($amount, $chargename, $daycounttotal) = &CalcFine($item,
209 $categorycode, $branch,
210 $start_dt, $end_dt );
212 Calculates the fine for a book.
214 The issuingrules table in the Koha database is a fine matrix, listing
215 the penalties for each type of patron for each type of item and each branch (e.g., the
216 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
217 members might get a longer grace period between the first and second
218 reminders that a book is overdue).
221 C<$item> is an item object (hashref).
223 C<$categorycode> is the category code (string) of the patron who currently has
226 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
228 C<$start_date> & C<$end_date> are DateTime objects
229 defining the date range over which to determine the fine.
231 Fines scripts should just supply the date range over which to calculate the fine.
233 C<&CalcFine> returns four values:
235 C<$amount> is the fine owed by the patron (see above).
237 C<$chargename> is the chargename field from the applicable record in
238 the categoryitem table, whatever that is.
240 C<$unitcount> is the number of chargeable units (days between start and end dates, Calendar adjusted where needed,
241 minus any applicable grace period, or hours)
243 FIXME - What is chargename supposed to be ?
245 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
246 or "Final Notice". But CalcFine never defined any value.
251 my ( $item, $bortype, $branchcode, $due_dt, $end_date ) = @_;
252 my $start_date = $due_dt->clone();
253 # get issuingrules (fines part will be used)
254 my $itemtype = $item->{itemtype} || $item->{itype};
255 my $data = C4::Circulation::GetIssuingRule($bortype, $itemtype, $branchcode);
256 my $fine_unit = $data->{lengthunit};
257 $fine_unit ||= 'days';
259 my $chargeable_units = _get_chargeable_units($fine_unit, $start_date, $end_date, $branchcode);
260 my $units_minus_grace = $chargeable_units - $data->{firstremind};
262 if ($data->{'chargeperiod'} && ($units_minus_grace > 0) ) {
263 if ( C4::Context->preference('FinesIncludeGracePeriod') ) {
264 $amount = int($chargeable_units / $data->{'chargeperiod'}) * $data->{'fine'};# TODO fine calc should be in cents
266 $amount = int($units_minus_grace / $data->{'chargeperiod'}) * $data->{'fine'};
269 # a zero (or null) chargeperiod or negative units_minus_grace value means no charge.
271 $amount = $data->{overduefinescap} if $data->{overduefinescap} && $amount > $data->{overduefinescap};
272 $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $units_minus_grace, $chargeable_units);
273 return ($amount, $data->{'chargename'}, $units_minus_grace, $chargeable_units);
274 # FIXME: chargename is NEVER populated anywhere.
278 =head2 _get_chargeable_units
280 _get_chargeable_units($unit, $start_date_ $end_date, $branchcode);
282 return integer value of units between C<$start_date> and C<$end_date>, factoring in holidays for C<$branchcode>.
284 C<$unit> is 'days' or 'hours' (default is 'days').
286 C<$start_date> and C<$end_date> are the two DateTimes to get the number of units between.
288 C<$branchcode> is the branch whose calendar to use for finding holidays.
292 sub _get_chargeable_units {
293 my ($unit, $dt1, $dt2, $branchcode) = @_;
294 my $charge_units = 0;
296 if ($unit eq 'hours') {
297 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
298 my $calendar = Koha::Calendar->new( branchcode => $branchcode );
299 $charge_duration = $calendar->hours_between( $dt1, $dt2 );
301 $charge_duration = $dt2->delta_ms( $dt1 );
303 if($charge_duration->in_units('hours') == 0 && $charge_duration->in_units('seconds') > 0){
306 return $charge_duration->in_units('hours');
309 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
310 my $calendar = Koha::Calendar->new( branchcode => $branchcode );
311 $charge_duration = $calendar->days_between( $dt1, $dt2 );
313 $charge_duration = $dt2->delta_days( $dt1 );
315 return $charge_duration->in_units('days');
320 =head2 GetSpecialHolidays
322 &GetSpecialHolidays($date_dues,$itemnumber);
324 return number of special days between date of the day and date due
326 C<$date_dues> is the envisaged date of book return.
328 C<$itemnumber> is the book's item number.
332 sub GetSpecialHolidays {
333 my ( $date_dues, $itemnumber ) = @_;
335 # calcul the today date
336 my $today = join "-", &Today();
338 # return the holdingbranch
339 my $iteminfo = GetIssuesIteminfo($itemnumber);
341 # use sql request to find all date between date_due and today
342 my $dbh = C4::Context->dbh;
344 qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
345 FROM `special_holidays`
346 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
347 AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
350 my @result = GetWdayFromItemnumber($itemnumber);
354 my $sth = $dbh->prepare($query);
355 $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
356 ; # FIXME: just use NOW() in SQL instead of passing in $today
358 while ( my $special_date = $sth->fetchrow_hashref ) {
359 push( @result_date, $special_date );
362 my $specialdaycount = scalar(@result_date);
364 for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
365 $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
366 ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
367 localtime($dateinsec);
368 for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
369 if ( $wday == ( $result[$j]->{'weekday'} ) ) {
375 return $specialdaycount;
378 =head2 GetRepeatableHolidays
380 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
382 return number of day closed between date of the day and date due
384 C<$date_dues> is the envisaged date of book return.
386 C<$itemnumber> is item number.
388 C<$difference> numbers of between day date of the day and date due
392 sub GetRepeatableHolidays {
393 my ( $date_dues, $itemnumber, $difference ) = @_;
394 my $dateinsec = UnixDate( $date_dues, "%o" );
395 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
396 localtime($dateinsec);
397 my @result = GetWdayFromItemnumber($itemnumber);
401 for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
404 for ( $j = 0 ; $j < $difference ; $j++ ) {
405 if ( $result[$i]->{'weekday'} == $k ) {
406 push( @dayclosedcount, $k );
409 ( $k = 0 ) if ( $k eq 7 );
412 return scalar(@dayclosedcount);
416 =head2 GetWayFromItemnumber
418 &Getwdayfromitemnumber($itemnumber);
420 return the different week day from repeatable_holidays table
422 C<$itemnumber> is item number.
426 sub GetWdayFromItemnumber {
427 my ($itemnumber) = @_;
428 my $iteminfo = GetIssuesIteminfo($itemnumber);
430 my $query = qq|SELECT weekday
431 FROM repeatable_holidays
434 my $sth = C4::Context->dbh->prepare($query);
436 $sth->execute( $iteminfo->{'branchcode'} );
437 while ( my $weekday = $sth->fetchrow_hashref ) {
438 push( @result, $weekday );
444 =head2 GetIssuesIteminfo
446 &GetIssuesIteminfo($itemnumber);
448 return all data from issues about item
450 C<$itemnumber> is item number.
454 sub GetIssuesIteminfo {
455 my ($itemnumber) = @_;
456 my $dbh = C4::Context->dbh;
457 my $query = qq|SELECT *
461 my $sth = $dbh->prepare($query);
462 $sth->execute($itemnumber);
463 my ($issuesinfo) = $sth->fetchrow_hashref;
470 &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
472 (Note: the following is mostly conjecture and guesswork.)
474 Updates the fine owed on an overdue book.
476 C<$itemnumber> is the book's item number.
478 C<$borrowernumber> is the borrower number of the patron who currently
479 has the book on loan.
481 C<$amount> is the current amount owed by the patron.
483 C<$type> will be used in the description of the fine.
485 C<$description> is a string that must be present in the description of
486 the fine. I think this is expected to be a date in DD/MM/YYYY format.
488 C<&UpdateFine> looks up the amount currently owed on the given item
489 and sets it to C<$amount>, creating, if necessary, a new entry in the
490 accountlines table of the Koha database.
495 # Question: Why should the caller have to
496 # specify both the item number and the borrower number? A book can't
497 # be on loan to two different people, so the item number should be
500 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
503 my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
504 $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
505 my $dbh = C4::Context->dbh;
506 # FIXME - What exactly is this query supposed to do? It looks up an
507 # entry in accountlines that matches the given item and borrower
508 # numbers, where the description contains $due, and where the
509 # account type has one of several values, but what does this _mean_?
510 # Does it look up existing fines for this item?
511 # FIXME - What are these various account types? ("FU", "O", "F", "M")
513 # "A" is Account Management Fee
518 # "FU" is Fine UPDATE??
520 # "REF" is Cash Refund
521 my $sth = $dbh->prepare(
522 "SELECT * FROM accountlines
523 WHERE borrowernumber=?
524 AND accounttype IN ('FU','O','F','M')"
526 $sth->execute( $borrowernumber );
528 my $total_amount_other = 0.00;
529 my $due_qr = qr/$due/;
530 # Cycle through the fines and
531 # - find line that relates to the requested $itemnum
532 # - accumulate fines for other items
533 # so we can update $itemnum fine taking in account fine caps
534 while (my $rec = $sth->fetchrow_hashref) {
535 if ($rec->{itemnumber} == $itemnum && $rec->{description} =~ /$due_qr/) {
537 warn "Not a unique accountlines record for item $itemnum borrower $borrowernumber";
543 $total_amount_other += $rec->{'amountoutstanding'};
546 if (my $maxfine = C4::Context->preference('MaxFine')) {
547 if ($total_amount_other + $amount > $maxfine) {
548 my $new_amount = $maxfine - $total_amount_other;
549 warn "Reducing fine for item $itemnum borrower $borrowernumber from $amount to $new_amount - MaxFine reached";
550 return if $new_amount <= 0.00;
552 $amount = $new_amount;
558 # we're updating an existing fine. Only modify if amount changed
559 # Note that in the current implementation, you cannot pay against an accruing fine
560 # (i.e. , of accounttype 'FU'). Doing so will break accrual.
561 if ( $data->{'amount'} != $amount ) {
562 my $diff = $amount - $data->{'amount'};
563 #3341: diff could be positive or negative!
564 my $out = $data->{'amountoutstanding'} + $diff;
567 SET date=now(), amount=?, amountoutstanding=?,
568 lastincrement=?, accounttype='FU'
569 WHERE borrowernumber=?
571 AND accounttype IN ('FU','O')
572 AND description LIKE ?
574 my $sth2 = $dbh->prepare($query);
575 # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
576 # LIMIT 1 added to prevent multiple affected lines
577 # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.
578 # But actually, we should just have a regular autoincrementing PK and forget accountline,
579 # including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
580 # FIXME: Why only 2 account types here?
581 $debug and print STDERR "UpdateFine query: $query\n" .
582 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
583 $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
585 # print "no update needed $data->{'amount'}"
588 my $sth4 = $dbh->prepare(
589 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
591 $sth4->execute($itemnum);
592 my $title = $sth4->fetchrow;
594 # # print "not in account";
595 # my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
598 # # FIXME - Make $accountno a scalar.
599 # my @accountno = $sth3->fetchrow_array;
603 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
604 my $desc = ($type ? "$type " : '') . "$title $due"; # FIXEDME, avoid whitespace prefix on empty $type
605 my $query = "INSERT INTO accountlines
606 (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
607 VALUES (?,?,now(),?,?,'FU',?,?,?)";
608 my $sth2 = $dbh->prepare($query);
609 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
610 $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
617 "due=".$due." amount=".$amount." itemnumber=".$itemnum
618 ) if C4::Context->preference("FinesLog");
623 $borrower = &BorType($borrowernumber);
625 Looks up a patron by borrower number.
627 C<$borrower> is a reference-to-hash whose keys are all of the fields
628 from the borrowers and categories tables of the Koha database. Thus,
629 C<$borrower> contains all information about both the borrower and
630 category he or she belongs to.
636 my ($borrowernumber) = @_;
637 my $dbh = C4::Context->dbh;
638 my $sth = $dbh->prepare(
639 "SELECT * from borrowers
640 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
641 WHERE borrowernumber=?"
643 $sth->execute($borrowernumber);
644 return $sth->fetchrow_hashref;
647 =head2 ReplacementCost
649 $cost = &ReplacementCost($itemnumber);
651 Returns the replacement cost of the item with the given item number.
656 sub ReplacementCost {
658 my $dbh = C4::Context->dbh;
660 $dbh->prepare("Select replacementprice from items where itemnumber=?");
661 $sth->execute($itemnum);
663 # FIXME - Use fetchrow_array or a slice.
664 my $data = $sth->fetchrow_hashref;
665 return ( $data->{'replacementprice'} );
670 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
672 return the total of fine
674 C<$itemnum> is item number
676 C<$borrowernumber> is the borrowernumber
682 my ( $itemnum, $borrowernumber ) = @_;
683 my $dbh = C4::Context->dbh();
684 my $query = q|SELECT sum(amountoutstanding) as fineamount FROM accountlines
685 where accounttype like 'F%'
686 AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?|;
687 my $sth = $dbh->prepare($query);
688 $sth->execute( $itemnum, $borrowernumber );
689 my $fine = $sth->fetchrow_hashref();
690 if ($fine->{fineamount}) {
691 return $fine->{fineamount};
696 sub ReplacementCost2 {
697 my ( $itemnum, $borrowernumber ) = @_;
698 my $dbh = C4::Context->dbh();
699 my $query = "SELECT amountoutstanding
701 WHERE accounttype like 'L'
702 AND amountoutstanding > 0
704 AND borrowernumber= ?";
705 my $sth = $dbh->prepare($query);
706 $sth->execute( $itemnum, $borrowernumber );
707 my $data = $sth->fetchrow_hashref();
708 return ( $data->{'amountoutstanding'} );
712 =head2 GetNextIdNotify
714 ($result) = &GetNextIdNotify($reference);
716 Returns the new file number
718 C<$result> contains the next file number
720 C<$reference> contains the beggining of file number
724 sub GetNextIdNotify {
725 my ($reference) = @_;
726 my $query = qq|SELECT max(notify_id)
728 WHERE notify_id like \"$reference%\"
731 # AND borrowernumber=?|;
732 my $dbh = C4::Context->dbh;
733 my $sth = $dbh->prepare($query);
735 my $result = $sth->fetchrow;
737 if ( $result eq '' ) {
738 ( $result = $reference . "01" );
741 $count = substr( $result, 6 ) + 1;
744 ( $count = "0" . $count );
746 $result = $reference . $count;
751 =head2 NumberNotifyId
753 (@notify) = &NumberNotifyId($borrowernumber);
755 Returns amount for all file per borrowers
756 C<@notify> array contains all file per borrowers
758 C<$notify_id> contains the file number for the borrower number nad item number
763 my ($borrowernumber)=@_;
764 my $dbh = C4::Context->dbh;
765 my $query=qq| SELECT distinct(notify_id)
767 WHERE borrowernumber=?|;
769 my $sth = $dbh->prepare($query);
770 $sth->execute($borrowernumber);
771 while ( my ($numberofnotify) = $sth->fetchrow ) {
772 push( @notify, $numberofnotify );
779 ($totalnotify) = &AmountNotify($notifyid);
781 Returns amount for all file per borrowers
782 C<$notifyid> is the file number
784 C<$totalnotify> contains amount of a file
786 C<$notify_id> contains the file number for the borrower number and item number
791 my ($notifyid,$borrowernumber)=@_;
792 my $dbh = C4::Context->dbh;
793 my $query=qq| SELECT sum(amountoutstanding)
795 WHERE notify_id=? AND borrowernumber = ?|;
796 my $sth=$dbh->prepare($query);
797 $sth->execute($notifyid,$borrowernumber);
798 my $totalnotify=$sth->fetchrow;
800 return ($totalnotify);
806 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
808 Returns the file number per borrower and itemnumber
810 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
811 from the items tables of the Koha database. Thus,
813 C<$itemnumber> contains the borrower categorycode
815 C<$notify_id> contains the file number for the borrower number nad item number
820 my ( $borrowernumber, $itemnumber ) = @_;
821 my $query = qq|SELECT notify_id
823 WHERE borrowernumber=?
825 AND (accounttype='FU' or accounttype='O')|;
826 my $dbh = C4::Context->dbh;
827 my $sth = $dbh->prepare($query);
828 $sth->execute( $borrowernumber, $itemnumber );
829 my ($notify_id) = $sth->fetchrow;
834 =head2 CreateItemAccountLine
836 () = &CreateItemAccountLine($borrowernumber, $itemnumber, $date, $amount,
837 $description, $accounttype, $amountoutstanding,
838 $timestamp, $notify_id, $level);
840 update the account lines with file number or with file level
842 C<$items> is a reference-to-hash whose keys are all of the fields
843 from the items tables of the Koha database. Thus,
845 C<$itemnumber> contains the item number
847 C<$borrowernumber> contains the borrower number
849 C<$date> contains the date of the day
851 C<$amount> contains item price
853 C<$description> contains the descritpion of accounttype
855 C<$accounttype> contains the account type
857 C<$amountoutstanding> contains the $amountoutstanding
859 C<$timestamp> contains the timestamp with time and the date of the day
861 C<$notify_id> contains the file number
863 C<$level> contains the file level
867 sub CreateItemAccountLine {
869 $borrowernumber, $itemnumber, $date, $amount,
870 $description, $accounttype, $amountoutstanding, $timestamp,
873 my $dbh = C4::Context->dbh;
874 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
875 my $query = "INSERT into accountlines
876 (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
878 (?,?,?,?,?,?,?,?,?,?,?)";
880 my $sth = $dbh->prepare($query);
882 $borrowernumber, $nextaccntno, $itemnumber,
883 $date, $amount, $description,
884 $accounttype, $amountoutstanding, $timestamp,
889 =head2 UpdateAccountLines
891 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
893 update the account lines with file number or with file level
895 C<$items> is a reference-to-hash whose keys are all of the fields
896 from the items tables of the Koha database. Thus,
898 C<$itemnumber> contains the item number
900 C<$notify_id> contains the file number
902 C<$notify_level> contains the file level
904 C<$borrowernumber> contains the borrowernumber
908 sub UpdateAccountLines {
909 my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
911 if ( $notify_id eq '' ) {
912 $query = qq|UPDATE accountlines
914 WHERE borrowernumber=? AND itemnumber=?
915 AND (accounttype='FU' or accounttype='O')|;
917 $query = qq|UPDATE accountlines
918 SET notify_id=?, notify_level=?
919 WHERE borrowernumber=?
921 AND (accounttype='FU' or accounttype='O')|;
924 my $sth = C4::Context->dbh->prepare($query);
925 if ( $notify_id eq '' ) {
926 $sth->execute( $notify_level, $borrowernumber, $itemnumber );
928 $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
934 ($items) = &GetItems($itemnumber);
936 Returns the list of all delays from overduerules.
938 C<$items> is a reference-to-hash whose keys are all of the fields
939 from the items tables of the Koha database. Thus,
941 C<$itemnumber> contains the borrower categorycode
945 # FIXME: This is a bad function to have here.
946 # Shouldn't it be in C4::Items?
947 # Shouldn't it be called GetItem since you only get 1 row?
948 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
951 my $itemnumber = shift or return;
952 my $query = qq|SELECT *
955 my $sth = C4::Context->dbh->prepare($query);
956 $sth->execute($itemnumber);
957 my ($items) = $sth->fetchrow_hashref;
961 =head2 GetOverdueDelays
963 (@delays) = &GetOverdueDelays($categorycode);
965 Returns the list of all delays from overduerules.
967 C<@delays> it's an array contains the three delays from overduerules table
969 C<$categorycode> contains the borrower categorycode
973 sub GetOverdueDelays {
975 my $query = qq|SELECT delay1,delay2,delay3
977 WHERE categorycode=?|;
978 my $sth = C4::Context->dbh->prepare($query);
979 $sth->execute($category);
980 my (@delays) = $sth->fetchrow_array;
984 =head2 GetBranchcodesWithOverdueRules
986 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
988 returns a list of branch codes for branches with overdue rules defined.
992 sub GetBranchcodesWithOverdueRules {
993 my $dbh = C4::Context->dbh;
994 my $rqoverduebranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode <> '' ORDER BY branchcode");
995 $rqoverduebranches->execute;
996 my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
998 my $availbranches = C4::Branch::GetBranches();
999 @branches = keys %$availbranches;
1004 =head2 CheckAccountLineLevelInfo
1006 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
1008 Check and Returns the list of all overdue books.
1010 C<$exist> contains number of line in accounlines
1011 with the same .biblionumber,itemnumber,accounttype,and notify_level
1013 C<$borrowernumber> contains the borrower number
1015 C<$itemnumber> contains item number
1017 C<$accounttype> contains account type
1019 C<$notify_level> contains the accountline level
1024 sub CheckAccountLineLevelInfo {
1025 my ( $borrowernumber, $itemnumber, $level ) = @_;
1026 my $dbh = C4::Context->dbh;
1027 my $query = qq|SELECT count(*)
1029 WHERE borrowernumber =?
1031 AND notify_level=?|;
1032 my $sth = $dbh->prepare($query);
1033 $sth->execute( $borrowernumber, $itemnumber, $level );
1034 my ($exist) = $sth->fetchrow;
1038 =head2 GetOverduerules
1040 ($overduerules) = &GetOverduerules($categorycode);
1042 Returns the value of borrowers (debarred or not) with notify level
1044 C<$overduerules> return value of debbraed field in overduerules table
1046 C<$category> contains the borrower categorycode
1048 C<$notify_level> contains the notify level
1052 sub GetOverduerules {
1053 my ( $category, $notify_level ) = @_;
1054 my $dbh = C4::Context->dbh;
1055 my $query = qq|SELECT debarred$notify_level
1057 WHERE categorycode=?|;
1058 my $sth = $dbh->prepare($query);
1059 $sth->execute($category);
1060 my ($overduerules) = $sth->fetchrow;
1061 return ($overduerules);
1065 =head2 CheckBorrowerDebarred
1067 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1069 Check if the borrowers is already debarred
1071 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1073 C<$borrowernumber> contains the borrower number
1077 # FIXME: Shouldn't this be in C4::Members?
1078 sub CheckBorrowerDebarred {
1079 my ($borrowernumber) = @_;
1080 my $dbh = C4::Context->dbh;
1084 WHERE borrowernumber=?
1085 AND debarred > NOW()
1087 my $sth = $dbh->prepare($query);
1088 $sth->execute($borrowernumber);
1089 my $debarredstatus = $sth->fetchrow;
1090 return $debarredstatus;
1094 =head2 CheckExistantNotifyid
1096 ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1098 Check and Returns the notify id if exist else return 0.
1100 C<$exist> contains a notify_id
1102 C<$borrowernumber> contains the borrower number
1104 C<$date_due> contains the date of item return
1109 sub CheckExistantNotifyid {
1110 my ( $borrowernumber, $date_due ) = @_;
1111 my $dbh = C4::Context->dbh;
1112 my $query = qq|SELECT notify_id FROM accountlines
1113 LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1114 WHERE accountlines.borrowernumber =?
1116 my $sth = $dbh->prepare($query);
1117 $sth->execute( $borrowernumber, $date_due );
1118 return $sth->fetchrow || 0;
1121 =head2 CheckAccountLineItemInfo
1123 ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1125 Check and Returns the list of all overdue items from the same file number(notify_id).
1127 C<$exist> contains number of line in accounlines
1128 with the same .biblionumber,itemnumber,accounttype,notify_id
1130 C<$borrowernumber> contains the borrower number
1132 C<$itemnumber> contains item number
1134 C<$accounttype> contains account type
1136 C<$notify_id> contains the file number
1140 sub CheckAccountLineItemInfo {
1141 my ( $borrowernumber, $itemnumber, $accounttype, $notify_id ) = @_;
1142 my $dbh = C4::Context->dbh;
1143 my $query = qq|SELECT count(*) FROM accountlines
1144 WHERE borrowernumber =?
1148 my $sth = $dbh->prepare($query);
1149 $sth->execute( $borrowernumber, $itemnumber, $accounttype, $notify_id );
1150 my ($exist) = $sth->fetchrow;
1154 =head2 CheckItemNotify
1156 Sql request to check if the document has alreday been notified
1157 this function is not exported, only used with GetOverduesForBranch
1161 sub CheckItemNotify {
1162 my ($notify_id,$notify_level,$itemnumber) = @_;
1163 my $dbh = C4::Context->dbh;
1164 my $sth = $dbh->prepare("
1168 AND notify_level = ?
1169 AND itemnumber = ? ");
1170 $sth->execute($notify_id,$notify_level,$itemnumber);
1171 my $notified = $sth->fetchrow;
1175 =head2 GetOverduesForBranch
1177 Sql request for display all information for branchoverdues.pl
1178 2 possibilities : with or without location .
1179 display is filtered by branch
1181 FIXME: This function should be renamed.
1185 sub GetOverduesForBranch {
1186 my ( $branch, $location) = @_;
1187 my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype ";
1188 my $dbh = C4::Context->dbh;
1191 borrowers.borrowernumber,
1193 borrowers.firstname,
1198 biblio.biblionumber,
1202 branches.branchname,
1205 items.itemcallnumber,
1208 itemtypes.description,
1209 accountlines.notify_id,
1210 accountlines.notify_level,
1211 accountlines.amountoutstanding
1213 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber
1214 AND issues.borrowernumber = accountlines.borrowernumber
1215 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1216 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1217 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1218 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1219 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1220 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1221 WHERE (accountlines.amountoutstanding != '0.000000')
1222 AND (accountlines.accounttype = 'FU' )
1223 AND (issues.branchcode = ? )
1224 AND (issues.date_due < NOW())
1230 $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1231 $sth->execute($branch, $location);
1233 $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1234 $sth->execute($branch);
1236 while ( my $data = $sth->fetchrow_hashref ) {
1237 #check if the document has already been notified
1238 my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1239 if ($countnotify eq '0') {
1240 $getoverdues[$i] = $data;
1244 return (@getoverdues);
1248 =head2 AddNotifyLine
1250 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1252 Create a line into notify, if the method is phone, the notification_send_date is implemented to
1257 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1258 my $dbh = C4::Context->dbh;
1259 if ( $method eq "phone" ) {
1260 my $sth = $dbh->prepare(
1261 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1262 VALUES (?,?,now(),now(),?,?,?)"
1264 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1268 my $sth = $dbh->prepare(
1269 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1270 VALUES (?,?,now(),?,?,?)"
1272 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1278 =head2 RemoveNotifyLine
1280 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1282 Cancel a notification
1286 sub RemoveNotifyLine {
1287 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1288 my $dbh = C4::Context->dbh;
1289 my $sth = $dbh->prepare(
1290 "DELETE FROM notifys
1296 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1305 Koha Development Team <http://koha-community.org/>