Bug 5931 Paging and sorting saved reports table
[koha.git] / C4 / Overdues.pm
bloba9af9d61e53010a3efff0bc1ad1dec7ef9725c24
1 package C4::Overdues;
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
12 # version.
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.
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use Date::Calc qw/Today Date_to_Days/;
25 use Date::Manip qw/UnixDate/;
26 use C4::Circulation;
27 use C4::Context;
28 use C4::Accounts;
29 use C4::Log; # logaction
30 use C4::Debug;
32 use vars qw($VERSION @ISA @EXPORT);
34 BEGIN {
35 # set the version for version checking
36 $VERSION = 3.01;
37 require Exporter;
38 @ISA = qw(Exporter);
39 # subs to rename (and maybe merge some...)
40 push @EXPORT, qw(
41 &CalcFine
42 &Getoverdues
43 &checkoverdues
44 &CheckAccountLineLevelInfo
45 &CheckAccountLineItemInfo
46 &CheckExistantNotifyid
47 &GetNextIdNotify
48 &GetNotifyId
49 &NumberNotifyId
50 &AmountNotify
51 &UpdateAccountLines
52 &UpdateFine
53 &GetOverdueDelays
54 &GetOverduerules
55 &GetFine
56 &CreateItemAccountLine
57 &ReplacementCost2
59 &CheckItemNotify
60 &GetOverduesForBranch
61 &RemoveNotifyLine
62 &AddNotifyLine
64 # subs to remove
65 push @EXPORT, qw(
66 &BorType
69 # check that an equivalent don't exist already before moving
71 # subs to move to Circulation.pm
72 push @EXPORT, qw(
73 &GetIssuesIteminfo
76 # &GetIssuingRules - delete.
77 # use C4::Circulation::GetIssuingRule instead.
79 # subs to move to Members.pm
80 push @EXPORT, qw(
81 &CheckBorrowerDebarred
82 &UpdateBorrowerDebarred
84 # subs to move to Biblio.pm
85 push @EXPORT, qw(
86 &GetItems
87 &ReplacementCost
91 =head1 NAME
93 C4::Circulation::Fines - Koha module dealing with fines
95 =head1 SYNOPSIS
97 use C4::Overdues;
99 =head1 DESCRIPTION
101 This module contains several functions for dealing with fines for
102 overdue items. It is primarily used by the 'misc/fines2.pl' script.
104 =head1 FUNCTIONS
106 =head2 Getoverdues
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
114 Koha database.
116 =cut
119 sub Getoverdues {
120 my $params = shift;
121 my $dbh = C4::Context->dbh;
122 my $statement;
123 if ( C4::Context->preference('item-level_itypes') ) {
124 $statement = "
125 SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode
126 FROM issues
127 LEFT JOIN items USING (itemnumber)
128 WHERE date_due < CURDATE()
130 } else {
131 $statement = "
132 SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode
133 FROM issues
134 LEFT JOIN items USING (itemnumber)
135 LEFT JOIN biblioitems USING (biblioitemnumber)
136 WHERE date_due < CURDATE()
140 my @bind_parameters;
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({});
158 =head2 checkoverdues
160 ($count, $overdueitems) = checkoverdues($borrowernumber);
162 Returns a count and a list of overdueitems for a given borrowernumber
164 =cut
166 sub checkoverdues {
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
182 =head2 CalcFine
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
200 the book.
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.
231 =cut
233 sub CalcFine {
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'),
240 ($dues || '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;
245 my $amount = 0;
246 my $daystocharge;
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);
250 if($difference) {
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;
257 } else {
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 );
262 } else {
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'};
270 } else {
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.
290 =cut
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;
303 my $query =
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') <= ?
308 AND branchcode=?
310 my @result = GetWdayFromItemnumber($itemnumber);
311 my @result_date;
312 my $wday;
313 my $dateinsec;
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'} ) ) {
330 $specialdaycount--;
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
350 =cut
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);
358 my @dayclosedcount;
359 my $j;
361 for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
362 my $k = $wday;
364 for ( $j = 0 ; $j < $difference ; $j++ ) {
365 if ( $result[$i]->{'weekday'} == $k ) {
366 push( @dayclosedcount, $k );
368 $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.
384 =cut
386 sub GetWdayFromItemnumber {
387 my ($itemnumber) = @_;
388 my $iteminfo = GetIssuesIteminfo($itemnumber);
389 my @result;
390 my $query = qq|SELECT weekday
391 FROM repeatable_holidays
392 WHERE branchcode=?
394 my $sth = C4::Context->dbh->prepare($query);
396 $sth->execute( $iteminfo->{'branchcode'} );
397 while ( my $weekday = $sth->fetchrow_hashref ) {
398 push( @result, $weekday );
400 return @result;
404 =head2 GetIssuesIteminfo
406 &GetIssuesIteminfo($itemnumber);
408 return all data from issues about item
410 C<$itemnumber> is item number.
412 =cut
414 sub GetIssuesIteminfo {
415 my ($itemnumber) = @_;
416 my $dbh = C4::Context->dbh;
417 my $query = qq|SELECT *
418 FROM issues
419 WHERE itemnumber=?
421 my $sth = $dbh->prepare($query);
422 $sth->execute($itemnumber);
423 my ($issuesinfo) = $sth->fetchrow_hashref;
424 return $issuesinfo;
428 =head2 UpdateFine
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.
452 =cut
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
458 # sufficient.
460 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
462 sub UpdateFine {
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")
472 # "L" is LOST item
473 # "A" is Account Management Fee
474 # "N" is New Card
475 # "M" is Sundry
476 # "O" is Overdue ??
477 # "F" is Fine ??
478 # "FU" is Fine UPDATE??
479 # "Pay" is Payment
480 # "REF" is Cash Refund
481 my $sth = $dbh->prepare(
482 "SELECT * FROM accountlines
483 WHERE itemnumber=?
484 AND borrowernumber=?
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;
499 my $query = "
500 UPDATE accountlines
501 SET date=now(), amount=?, amountoutstanding=?,
502 lastincrement=?, accounttype='FU'
503 WHERE borrowernumber=?
504 AND itemnumber=?
505 AND accounttype IN ('FU','O')
506 AND description LIKE ?
507 LIMIT 1 ";
508 my $sth2 = $dbh->prepare($query);
509 # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
510 # LIMIT 1 added to prevent multiple affected lines
511 # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.
512 # But actually, we should just have a regular autoincrementing PK and forget accountline,
513 # including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
514 # FIXME: Why only 2 account types here?
515 $debug and print STDERR "UpdateFine query: $query\n" .
516 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
517 $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
518 } else {
519 # print "no update needed $data->{'amount'}"
521 } else {
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");
530 # $sth3->execute;
532 # # FIXME - Make $accountno a scalar.
533 # my @accountno = $sth3->fetchrow_array;
534 # $sth3->finish;
535 # $accountno[0]++;
536 # begin transaction
537 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
538 my $desc = ($type ? "$type " : '') . "$title $due"; # FIXEDME, avoid whitespace prefix on empty $type
539 my $query = "INSERT INTO accountlines
540 (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
541 VALUES (?,?,now(),?,?,'FU',?,?,?)";
542 my $sth2 = $dbh->prepare($query);
543 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
544 $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
546 # logging action
547 &logaction(
548 "FINES",
549 $type,
550 $borrowernumber,
551 "due=".$due." amount=".$amount." itemnumber=".$itemnum
552 ) if C4::Context->preference("FinesLog");
555 =head2 BorType
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.
566 =cut
569 sub BorType {
570 my ($borrowernumber) = @_;
571 my $dbh = C4::Context->dbh;
572 my $sth = $dbh->prepare(
573 "SELECT * from borrowers
574 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
575 WHERE borrowernumber=?"
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.
587 =cut
590 sub ReplacementCost {
591 my ($itemnum) = @_;
592 my $dbh = C4::Context->dbh;
593 my $sth =
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'} );
602 =head2 GetFine
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
612 =cut
615 sub GetFine {
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.
644 =cut
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 *
651 FROM issuingrules
652 WHERE issuingrules.itemtype=?
653 AND issuingrules.categorycode=?
655 my $sth = $dbh->prepare($query);
656 # print $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
666 FROM accountlines
667 WHERE accounttype like 'L'
668 AND amountoutstanding > 0
669 AND itemnumber = ?
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
688 =cut
690 sub GetNextIdNotify {
691 my ($reference) = @_;
692 my $query = qq|SELECT max(notify_id)
693 FROM accountlines
694 WHERE notify_id like \"$reference%\"
697 # AND borrowernumber=?|;
698 my $dbh = C4::Context->dbh;
699 my $sth = $dbh->prepare($query);
700 $sth->execute();
701 my $result = $sth->fetchrow;
702 my $count;
703 if ( $result eq '' ) {
704 ( $result = $reference . "01" );
706 else {
707 $count = substr( $result, 6 ) + 1;
709 if ( $count < 10 ) {
710 ( $count = "0" . $count );
712 $result = $reference . $count;
714 return $result;
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
726 =cut
728 sub NumberNotifyId{
729 my ($borrowernumber)=@_;
730 my $dbh = C4::Context->dbh;
731 my $query=qq| SELECT distinct(notify_id)
732 FROM accountlines
733 WHERE borrowernumber=?|;
734 my @notify;
735 my $sth = $dbh->prepare($query);
736 $sth->execute($borrowernumber);
737 while ( my ($numberofnotify) = $sth->fetchrow ) {
738 push( @notify, $numberofnotify );
740 return (@notify);
743 =head2 AmountNotify
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
754 =cut
756 sub AmountNotify{
757 my ($notifyid,$borrowernumber)=@_;
758 my $dbh = C4::Context->dbh;
759 my $query=qq| SELECT sum(amountoutstanding)
760 FROM accountlines
761 WHERE notify_id=? AND borrowernumber = ?|;
762 my $sth=$dbh->prepare($query);
763 $sth->execute($notifyid,$borrowernumber);
764 my $totalnotify=$sth->fetchrow;
765 $sth->finish;
766 return ($totalnotify);
770 =head2 GetNotifyId
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
783 =cut
785 sub GetNotifyId {
786 my ( $borrowernumber, $itemnumber ) = @_;
787 my $query = qq|SELECT notify_id
788 FROM accountlines
789 WHERE borrowernumber=?
790 AND itemnumber=?
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;
796 $sth->finish;
797 return ($notify_id);
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
831 =cut
833 sub CreateItemAccountLine {
834 my (
835 $borrowernumber, $itemnumber, $date, $amount,
836 $description, $accounttype, $amountoutstanding, $timestamp,
837 $notify_id, $level
838 ) = @_;
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)
843 VALUES
844 (?,?,?,?,?,?,?,?,?,?,?)";
846 my $sth = $dbh->prepare($query);
847 $sth->execute(
848 $borrowernumber, $nextaccntno, $itemnumber,
849 $date, $amount, $description,
850 $accounttype, $amountoutstanding, $timestamp,
851 $notify_id, $level
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
872 =cut
874 sub UpdateAccountLines {
875 my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
876 my $query;
877 if ( $notify_id eq '' ) {
878 $query = qq|UPDATE accountlines
879 SET notify_level=?
880 WHERE borrowernumber=? AND itemnumber=?
881 AND (accounttype='FU' or accounttype='O')|;
882 } else {
883 $query = qq|UPDATE accountlines
884 SET notify_id=?, notify_level=?
885 WHERE borrowernumber=?
886 AND itemnumber=?
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 );
893 } else {
894 $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
898 =head2 GetItems
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
909 =cut
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?
916 sub GetItems {
917 my $itemnumber = shift or return;
918 my $query = qq|SELECT *
919 FROM items
920 WHERE itemnumber=?|;
921 my $sth = C4::Context->dbh->prepare($query);
922 $sth->execute($itemnumber);
923 my ($items) = $sth->fetchrow_hashref;
924 return ($items);
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
937 =cut
939 sub GetOverdueDelays {
940 my ($category) = @_;
941 my $query = qq|SELECT delay1,delay2,delay3
942 FROM overduerules
943 WHERE categorycode=?|;
944 my $sth = C4::Context->dbh->prepare($query);
945 $sth->execute($category);
946 my (@delays) = $sth->fetchrow_array;
947 return (@delays);
950 =head2 GetBranchcodesWithOverdueRules
952 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
954 returns a list of branch codes for branches with overdue rules defined.
956 =cut
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 <> ''");
961 $rqoverduebranches->execute;
962 my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
963 return @branches;
966 =head2 CheckAccountLineLevelInfo
968 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
970 Check and Returns the list of all overdue books.
972 C<$exist> contains number of line in accounlines
973 with the same .biblionumber,itemnumber,accounttype,and notify_level
975 C<$borrowernumber> contains the borrower number
977 C<$itemnumber> contains item number
979 C<$accounttype> contains account type
981 C<$notify_level> contains the accountline level
984 =cut
986 sub CheckAccountLineLevelInfo {
987 my ( $borrowernumber, $itemnumber, $level ) = @_;
988 my $dbh = C4::Context->dbh;
989 my $query = qq|SELECT count(*)
990 FROM accountlines
991 WHERE borrowernumber =?
992 AND itemnumber = ?
993 AND notify_level=?|;
994 my $sth = $dbh->prepare($query);
995 $sth->execute( $borrowernumber, $itemnumber, $level );
996 my ($exist) = $sth->fetchrow;
997 return ($exist);
1000 =head2 GetOverduerules
1002 ($overduerules) = &GetOverduerules($categorycode);
1004 Returns the value of borrowers (debarred or not) with notify level
1006 C<$overduerules> return value of debbraed field in overduerules table
1008 C<$category> contains the borrower categorycode
1010 C<$notify_level> contains the notify level
1012 =cut
1014 sub GetOverduerules {
1015 my ( $category, $notify_level ) = @_;
1016 my $dbh = C4::Context->dbh;
1017 my $query = qq|SELECT debarred$notify_level
1018 FROM overduerules
1019 WHERE categorycode=?|;
1020 my $sth = $dbh->prepare($query);
1021 $sth->execute($category);
1022 my ($overduerules) = $sth->fetchrow;
1023 return ($overduerules);
1027 =head2 CheckBorrowerDebarred
1029 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1031 Check if the borrowers is already debarred
1033 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1035 C<$borrowernumber> contains the borrower number
1037 =cut
1039 # FIXME: Shouldn't this be in C4::Members?
1040 sub CheckBorrowerDebarred {
1041 my ($borrowernumber) = @_;
1042 my $dbh = C4::Context->dbh;
1043 my $query = qq|
1044 SELECT debarred
1045 FROM borrowers
1046 WHERE borrowernumber=?
1048 my $sth = $dbh->prepare($query);
1049 $sth->execute($borrowernumber);
1050 my ($debarredstatus) = $sth->fetchrow;
1051 return ( $debarredstatus eq '1' ? 1 : 0 );
1054 =head2 UpdateBorrowerDebarred
1056 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
1058 update status of borrowers in borrowers table (field debarred)
1060 C<$borrowernumber> borrower number
1062 =cut
1064 sub UpdateBorrowerDebarred{
1065 my($borrowernumber) = @_;
1066 my $dbh = C4::Context->dbh;
1067 my $query=qq|UPDATE borrowers
1068 SET debarred='1'
1069 WHERE borrowernumber=?
1071 my $sth=$dbh->prepare($query);
1072 $sth->execute($borrowernumber);
1073 $sth->finish;
1074 return 1;
1077 =head2 CheckExistantNotifyid
1079 ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1081 Check and Returns the notify id if exist else return 0.
1083 C<$exist> contains a notify_id
1085 C<$borrowernumber> contains the borrower number
1087 C<$date_due> contains the date of item return
1090 =cut
1092 sub CheckExistantNotifyid {
1093 my ( $borrowernumber, $date_due ) = @_;
1094 my $dbh = C4::Context->dbh;
1095 my $query = qq|SELECT notify_id FROM accountlines
1096 LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1097 WHERE accountlines.borrowernumber =?
1098 AND date_due = ?|;
1099 my $sth = $dbh->prepare($query);
1100 $sth->execute( $borrowernumber, $date_due );
1101 return $sth->fetchrow || 0;
1104 =head2 CheckAccountLineItemInfo
1106 ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1108 Check and Returns the list of all overdue items from the same file number(notify_id).
1110 C<$exist> contains number of line in accounlines
1111 with the same .biblionumber,itemnumber,accounttype,notify_id
1113 C<$borrowernumber> contains the borrower number
1115 C<$itemnumber> contains item number
1117 C<$accounttype> contains account type
1119 C<$notify_id> contains the file number
1121 =cut
1123 sub CheckAccountLineItemInfo {
1124 my ( $borrowernumber, $itemnumber, $accounttype, $notify_id ) = @_;
1125 my $dbh = C4::Context->dbh;
1126 my $query = qq|SELECT count(*) FROM accountlines
1127 WHERE borrowernumber =?
1128 AND itemnumber = ?
1129 AND accounttype= ?
1130 AND notify_id = ?|;
1131 my $sth = $dbh->prepare($query);
1132 $sth->execute( $borrowernumber, $itemnumber, $accounttype, $notify_id );
1133 my ($exist) = $sth->fetchrow;
1134 return ($exist);
1137 =head2 CheckItemNotify
1139 Sql request to check if the document has alreday been notified
1140 this function is not exported, only used with GetOverduesForBranch
1142 =cut
1144 sub CheckItemNotify {
1145 my ($notify_id,$notify_level,$itemnumber) = @_;
1146 my $dbh = C4::Context->dbh;
1147 my $sth = $dbh->prepare("
1148 SELECT COUNT(*)
1149 FROM notifys
1150 WHERE notify_id = ?
1151 AND notify_level = ?
1152 AND itemnumber = ? ");
1153 $sth->execute($notify_id,$notify_level,$itemnumber);
1154 my $notified = $sth->fetchrow;
1155 return ($notified);
1158 =head2 GetOverduesForBranch
1160 Sql request for display all information for branchoverdues.pl
1161 2 possibilities : with or without location .
1162 display is filtered by branch
1164 FIXME: This function should be renamed.
1166 =cut
1168 sub GetOverduesForBranch {
1169 my ( $branch, $location) = @_;
1170 my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype ";
1171 my $dbh = C4::Context->dbh;
1172 my $select = "
1173 SELECT
1174 borrowers.borrowernumber,
1175 borrowers.surname,
1176 borrowers.firstname,
1177 borrowers.phone,
1178 borrowers.email,
1179 biblio.title,
1180 biblio.author,
1181 biblio.biblionumber,
1182 issues.date_due,
1183 issues.returndate,
1184 issues.branchcode,
1185 branches.branchname,
1186 items.barcode,
1187 items.homebranch,
1188 items.itemcallnumber,
1189 items.location,
1190 items.itemnumber,
1191 itemtypes.description,
1192 accountlines.notify_id,
1193 accountlines.notify_level,
1194 accountlines.amountoutstanding
1195 FROM accountlines
1196 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber
1197 AND issues.borrowernumber = accountlines.borrowernumber
1198 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1199 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1200 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1201 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1202 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1203 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1204 WHERE (accountlines.amountoutstanding != '0.000000')
1205 AND (accountlines.accounttype = 'FU' )
1206 AND (issues.branchcode = ? )
1207 AND (issues.date_due < CURDATE())
1209 my @getoverdues;
1210 my $i = 0;
1211 my $sth;
1212 if ($location) {
1213 $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1214 $sth->execute($branch, $location);
1215 } else {
1216 $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1217 $sth->execute($branch);
1219 while ( my $data = $sth->fetchrow_hashref ) {
1220 #check if the document has already been notified
1221 my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1222 if ($countnotify eq '0') {
1223 $getoverdues[$i] = $data;
1224 $i++;
1227 return (@getoverdues);
1231 =head2 AddNotifyLine
1233 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1235 Create a line into notify, if the method is phone, the notification_send_date is implemented to
1237 =cut
1239 sub AddNotifyLine {
1240 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1241 my $dbh = C4::Context->dbh;
1242 if ( $method eq "phone" ) {
1243 my $sth = $dbh->prepare(
1244 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1245 VALUES (?,?,now(),now(),?,?,?)"
1247 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1248 $notifyId );
1250 else {
1251 my $sth = $dbh->prepare(
1252 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1253 VALUES (?,?,now(),?,?,?)"
1255 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1256 $notifyId );
1258 return 1;
1261 =head2 RemoveNotifyLine
1263 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1265 Cancel a notification
1267 =cut
1269 sub RemoveNotifyLine {
1270 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1271 my $dbh = C4::Context->dbh;
1272 my $sth = $dbh->prepare(
1273 "DELETE FROM notifys
1274 WHERE
1275 borrowernumber=?
1276 AND itemnumber=?
1277 AND notify_date=?"
1279 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1280 return 1;
1284 __END__
1286 =head1 AUTHOR
1288 Koha Development Team <http://koha-community.org/>
1290 =cut