Fix bug on opac-detail.pl with switch statement
[koha.git] / C4 / Overdues.pm
blob032ca938e16010c9d5b8f23fa5e1b5192157e21f
1 package C4::Overdues;
4 # Copyright 2000-2002 Katipo Communications
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use Date::Calc qw/Today Date_to_Days/;
24 use Date::Manip qw/UnixDate/;
25 use C4::Circulation;
26 use C4::Context;
27 use C4::Accounts;
28 use C4::Log; # logaction
29 use C4::Debug;
31 use vars qw($VERSION @ISA @EXPORT);
33 BEGIN {
34 # set the version for version checking
35 $VERSION = 3.01;
36 require Exporter;
37 @ISA = qw(Exporter);
38 # subs to rename (and maybe merge some...)
39 push @EXPORT, qw(
40 &CalcFine
41 &Getoverdues
42 &checkoverdues
43 &CheckAccountLineLevelInfo
44 &CheckAccountLineItemInfo
45 &CheckExistantNotifyid
46 &GetNextIdNotify
47 &GetNotifyId
48 &NumberNotifyId
49 &AmountNotify
50 &UpdateAccountLines
51 &UpdateFine
52 &GetOverdueDelays
53 &GetOverduerules
54 &GetFine
55 &CreateItemAccountLine
56 &ReplacementCost2
58 &CheckItemNotify
59 &GetOverduesForBranch
60 &RemoveNotifyLine
61 &AddNotifyLine
63 # subs to remove
64 push @EXPORT, qw(
65 &BorType
68 # check that an equivalent don't exist already before moving
70 # subs to move to Circulation.pm
71 push @EXPORT, qw(
72 &GetIssuesIteminfo
75 # &GetIssuingRules - delete.
76 # use C4::Circulation::GetIssuingRule instead.
78 # subs to move to Members.pm
79 push @EXPORT, qw(
80 &CheckBorrowerDebarred
81 &UpdateBorrowerDebarred
83 # subs to move to Biblio.pm
84 push @EXPORT, qw(
85 &GetItems
86 &ReplacementCost
90 =head1 NAME
92 C4::Circulation::Fines - Koha module dealing with fines
94 =head1 SYNOPSIS
96 use C4::Overdues;
98 =head1 DESCRIPTION
100 This module contains several functions for dealing with fines for
101 overdue items. It is primarily used by the 'misc/fines2.pl' script.
103 =head1 FUNCTIONS
105 =head2 Getoverdues
107 $overdues = Getoverdues( { minimumdays => 1, maximumdays => 30 } );
109 Returns the list of all overdue books, with their itemtype.
111 C<$overdues> is a reference-to-array. Each element is a
112 reference-to-hash whose keys are the fields of the issues table in the
113 Koha database.
115 =cut
118 sub Getoverdues {
119 my $params = shift;
120 my $dbh = C4::Context->dbh;
121 my $statement;
122 if ( C4::Context->preference('item-level_itypes') ) {
123 $statement = "
124 SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode
125 FROM issues
126 LEFT JOIN items USING (itemnumber)
127 WHERE date_due < CURDATE()
129 } else {
130 $statement = "
131 SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode
132 FROM issues
133 LEFT JOIN items USING (itemnumber)
134 LEFT JOIN biblioitems USING (biblioitemnumber)
135 WHERE date_due < CURDATE()
139 my @bind_parameters;
140 if ( exists $params->{'minimumdays'} and exists $params->{'maximumdays'} ) {
141 $statement .= ' AND TO_DAYS( NOW() )-TO_DAYS( date_due ) BETWEEN ? and ? ';
142 push @bind_parameters, $params->{'minimumdays'}, $params->{'maximumdays'};
143 } elsif ( exists $params->{'minimumdays'} ) {
144 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) > ? ';
145 push @bind_parameters, $params->{'minimumdays'};
146 } elsif ( exists $params->{'maximumdays'} ) {
147 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ? ';
148 push @bind_parameters, $params->{'maximumdays'};
150 $statement .= 'ORDER BY borrowernumber';
151 my $sth = $dbh->prepare( $statement );
152 $sth->execute( @bind_parameters );
153 return $sth->fetchall_arrayref({});
157 =head2 checkoverdues
159 ($count, $overdueitems) = checkoverdues($borrowernumber);
161 Returns a count and a list of overdueitems for a given borrowernumber
163 =cut
165 sub checkoverdues {
166 my $borrowernumber = shift or return;
167 my $sth = C4::Context->dbh->prepare(
168 "SELECT * FROM issues
169 LEFT JOIN items ON issues.itemnumber = items.itemnumber
170 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
171 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
172 WHERE issues.borrowernumber = ?
173 AND issues.date_due < CURDATE()"
175 # FIXME: SELECT * across 4 tables? do we really need the marc AND marcxml blobs??
176 $sth->execute($borrowernumber);
177 my $results = $sth->fetchall_arrayref({});
178 return ( scalar(@$results), $results); # returning the count and the results is silly
181 =head2 CalcFine
183 ($amount, $chargename, $daycount, $daycounttotal) = &CalcFine($item,
184 $categorycode, $branch, $days_overdue,
185 $description, $start_date, $end_date );
187 Calculates the fine for a book.
189 The issuingrules table in the Koha database is a fine matrix, listing
190 the penalties for each type of patron for each type of item and each branch (e.g., the
191 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
192 members might get a longer grace period between the first and second
193 reminders that a book is overdue).
196 C<$item> is an item object (hashref).
198 C<$categorycode> is the category code (string) of the patron who currently has
199 the book.
201 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
203 C<$days_overdue> is the number of days elapsed since the book's due date.
204 NOTE: supplying days_overdue is deprecated.
206 C<$start_date> & C<$end_date> are C4::Dates objects
207 defining the date range over which to determine the fine.
208 Note that if these are defined, we ignore C<$difference> and C<$dues> ,
209 but retain these for backwards-comptibility with extant fines scripts.
211 Fines scripts should just supply the date range over which to calculate the fine.
213 C<&CalcFine> returns four values:
215 C<$amount> is the fine owed by the patron (see above).
217 C<$chargename> is the chargename field from the applicable record in
218 the categoryitem table, whatever that is.
220 C<$daycount> is the number of days between start and end dates, Calendar adjusted (where needed),
221 minus any applicable grace period.
223 C<$daycounttotal> is C<$daycount> without consideration of grace period.
225 FIXME - What is chargename supposed to be ?
227 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
228 or "Final Notice". But CalcFine never defined any value.
230 =cut
232 sub CalcFine {
233 my ( $item, $bortype, $branchcode, $difference ,$dues , $start_date, $end_date ) = @_;
234 $debug and warn sprintf("CalcFine(%s, %s, %s, %s, %s, %s, %s)",
235 ($item ? '{item}' : 'UNDEF'),
236 ($bortype || 'UNDEF'),
237 ($branchcode || 'UNDEF'),
238 ($difference || 'UNDEF'),
239 ($dues || 'UNDEF'),
240 ($start_date ? ($start_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF'),
241 ( $end_date ? ( $end_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF')
243 my $dbh = C4::Context->dbh;
244 my $amount = 0;
245 my $daystocharge;
246 # get issuingrules (fines part will be used)
247 $debug and warn sprintf("CalcFine calling GetIssuingRule(%s, %s, %s)", $bortype, $item->{'itemtype'}, $branchcode);
248 my $data = C4::Circulation::GetIssuingRule($bortype, $item->{'itemtype'}, $branchcode);
249 if($difference) {
250 # if $difference is supplied, the difference has already been calculated, but we still need to adjust for the calendar.
251 # use copy-pasted functions from calendar module. (deprecated -- these functions will be removed from C4::Overdues ).
252 my $countspecialday = &GetSpecialHolidays($dues,$item->{itemnumber});
253 my $countrepeatableday = &GetRepeatableHolidays($dues,$item->{itemnumber},$difference);
254 my $countalldayclosed = $countspecialday + $countrepeatableday;
255 $daystocharge = $difference - $countalldayclosed;
256 } else {
257 # if $difference is not supplied, we have C4::Dates objects giving us the date range, and we use the calendar module.
258 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
259 my $calendar = C4::Calendar->new( branchcode => $branchcode );
260 $daystocharge = $calendar->daysBetween( $start_date, $end_date );
261 } else {
262 $daystocharge = Date_to_Days(split('-',$end_date->output('iso'))) - Date_to_Days(split('-',$start_date->output('iso')));
265 # correct for grace period.
266 my $days_minus_grace = $daystocharge - $data->{'firstremind'};
267 if ($data->{'chargeperiod'} > 0 && $days_minus_grace > 0 ) {
268 $amount = int($daystocharge / $data->{'chargeperiod'}) * $data->{'fine'};
269 } else {
270 # a zero (or null) chargeperiod means no charge.
272 $amount = C4::Context->preference('maxFine') if(C4::Context->preference('maxFine') && ( $amount > C4::Context->preference('maxFine')));
273 $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
274 return ($amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
275 # FIXME: chargename is NEVER populated anywhere.
279 =head2 GetSpecialHolidays
281 &GetSpecialHolidays($date_dues,$itemnumber);
283 return number of special days between date of the day and date due
285 C<$date_dues> is the envisaged date of book return.
287 C<$itemnumber> is the book's item number.
289 =cut
291 sub GetSpecialHolidays {
292 my ( $date_dues, $itemnumber ) = @_;
294 # calcul the today date
295 my $today = join "-", &Today();
297 # return the holdingbranch
298 my $iteminfo = GetIssuesIteminfo($itemnumber);
300 # use sql request to find all date between date_due and today
301 my $dbh = C4::Context->dbh;
302 my $query =
303 qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
304 FROM `special_holidays`
305 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
306 AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
307 AND branchcode=?
309 my @result = GetWdayFromItemnumber($itemnumber);
310 my @result_date;
311 my $wday;
312 my $dateinsec;
313 my $sth = $dbh->prepare($query);
314 $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
315 ; # FIXME: just use NOW() in SQL instead of passing in $today
317 while ( my $special_date = $sth->fetchrow_hashref ) {
318 push( @result_date, $special_date );
321 my $specialdaycount = scalar(@result_date);
323 for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
324 $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
325 ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
326 localtime($dateinsec);
327 for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
328 if ( $wday == ( $result[$j]->{'weekday'} ) ) {
329 $specialdaycount--;
334 return $specialdaycount;
337 =head2 GetRepeatableHolidays
339 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
341 return number of day closed between date of the day and date due
343 C<$date_dues> is the envisaged date of book return.
345 C<$itemnumber> is item number.
347 C<$difference> numbers of between day date of the day and date due
349 =cut
351 sub GetRepeatableHolidays {
352 my ( $date_dues, $itemnumber, $difference ) = @_;
353 my $dateinsec = UnixDate( $date_dues, "%o" );
354 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
355 localtime($dateinsec);
356 my @result = GetWdayFromItemnumber($itemnumber);
357 my @dayclosedcount;
358 my $j;
360 for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
361 my $k = $wday;
363 for ( $j = 0 ; $j < $difference ; $j++ ) {
364 if ( $result[$i]->{'weekday'} == $k ) {
365 push( @dayclosedcount, $k );
367 $k++;
368 ( $k = 0 ) if ( $k eq 7 );
371 return scalar(@dayclosedcount);
375 =head2 GetWayFromItemnumber
377 &Getwdayfromitemnumber($itemnumber);
379 return the different week day from repeatable_holidays table
381 C<$itemnumber> is item number.
383 =cut
385 sub GetWdayFromItemnumber {
386 my ($itemnumber) = @_;
387 my $iteminfo = GetIssuesIteminfo($itemnumber);
388 my @result;
389 my $query = qq|SELECT weekday
390 FROM repeatable_holidays
391 WHERE branchcode=?
393 my $sth = C4::Context->dbh->prepare($query);
395 $sth->execute( $iteminfo->{'branchcode'} );
396 while ( my $weekday = $sth->fetchrow_hashref ) {
397 push( @result, $weekday );
399 return @result;
403 =head2 GetIssuesIteminfo
405 &GetIssuesIteminfo($itemnumber);
407 return all data from issues about item
409 C<$itemnumber> is item number.
411 =cut
413 sub GetIssuesIteminfo {
414 my ($itemnumber) = @_;
415 my $dbh = C4::Context->dbh;
416 my $query = qq|SELECT *
417 FROM issues
418 WHERE itemnumber=?
420 my $sth = $dbh->prepare($query);
421 $sth->execute($itemnumber);
422 my ($issuesinfo) = $sth->fetchrow_hashref;
423 return $issuesinfo;
427 =head2 UpdateFine
429 &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
431 (Note: the following is mostly conjecture and guesswork.)
433 Updates the fine owed on an overdue book.
435 C<$itemnumber> is the book's item number.
437 C<$borrowernumber> is the borrower number of the patron who currently
438 has the book on loan.
440 C<$amount> is the current amount owed by the patron.
442 C<$type> will be used in the description of the fine.
444 C<$description> is a string that must be present in the description of
445 the fine. I think this is expected to be a date in DD/MM/YYYY format.
447 C<&UpdateFine> looks up the amount currently owed on the given item
448 and sets it to C<$amount>, creating, if necessary, a new entry in the
449 accountlines table of the Koha database.
451 =cut
454 # Question: Why should the caller have to
455 # specify both the item number and the borrower number? A book can't
456 # be on loan to two different people, so the item number should be
457 # sufficient.
459 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
461 sub UpdateFine {
462 my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
463 $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
464 my $dbh = C4::Context->dbh;
465 # FIXME - What exactly is this query supposed to do? It looks up an
466 # entry in accountlines that matches the given item and borrower
467 # numbers, where the description contains $due, and where the
468 # account type has one of several values, but what does this _mean_?
469 # Does it look up existing fines for this item?
470 # FIXME - What are these various account types? ("FU", "O", "F", "M")
471 # "L" is LOST item
472 # "A" is Account Management Fee
473 # "N" is New Card
474 # "M" is Sundry
475 # "O" is Overdue ??
476 # "F" is Fine ??
477 # "FU" is Fine UPDATE??
478 # "Pay" is Payment
479 # "REF" is Cash Refund
480 my $sth = $dbh->prepare(
481 "SELECT * FROM accountlines
482 WHERE itemnumber=?
483 AND borrowernumber=?
484 AND accounttype IN ('FU','O','F','M')
485 AND description like ? "
487 $sth->execute( $itemnum, $borrowernumber, "%$due%" );
489 if ( my $data = $sth->fetchrow_hashref ) {
491 # we're updating an existing fine. Only modify if we're adding to the charge.
492 # Note that in the current implementation, you cannot pay against an accruing fine
493 # (i.e. , of accounttype 'FU'). Doing so will break accrual.
494 if ( $data->{'amount'} != $amount ) {
495 my $diff = $amount - $data->{'amount'};
496 $diff = 0 if ( $data->{amount} > $amount);
497 my $out = $data->{'amountoutstanding'} + $diff;
498 my $query = "
499 UPDATE accountlines
500 SET date=now(), amount=?, amountoutstanding=?,
501 lastincrement=?, accounttype='FU'
502 WHERE borrowernumber=?
503 AND itemnumber=?
504 AND accounttype IN ('FU','O')
505 AND description LIKE ?
506 LIMIT 1 ";
507 my $sth2 = $dbh->prepare($query);
508 # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
509 # LIMIT 1 added to prevent multiple affected lines
510 # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.
511 # But actually, we should just have a regular autoincrementing PK and forget accountline,
512 # including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
513 # FIXME: Why only 2 account types here?
514 $debug and print STDERR "UpdateFine query: $query\n" .
515 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
516 $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
517 } else {
518 # print "no update needed $data->{'amount'}"
520 } else {
521 my $sth4 = $dbh->prepare(
522 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
524 $sth4->execute($itemnum);
525 my $title = $sth4->fetchrow;
527 # # print "not in account";
528 # my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
529 # $sth3->execute;
531 # # FIXME - Make $accountno a scalar.
532 # my @accountno = $sth3->fetchrow_array;
533 # $sth3->finish;
534 # $accountno[0]++;
535 # begin transaction
536 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
537 my $desc = ($type ? "$type " : '') . "$title $due"; # FIXEDME, avoid whitespace prefix on empty $type
538 my $query = "INSERT INTO accountlines
539 (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
540 VALUES (?,?,now(),?,?,'FU',?,?,?)";
541 my $sth2 = $dbh->prepare($query);
542 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
543 $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
545 # logging action
546 &logaction(
547 "FINES",
548 $type,
549 $borrowernumber,
550 "due=".$due." amount=".$amount." itemnumber=".$itemnum
551 ) if C4::Context->preference("FinesLog");
554 =head2 BorType
556 $borrower = &BorType($borrowernumber);
558 Looks up a patron by borrower number.
560 C<$borrower> is a reference-to-hash whose keys are all of the fields
561 from the borrowers and categories tables of the Koha database. Thus,
562 C<$borrower> contains all information about both the borrower and
563 category he or she belongs to.
565 =cut
568 sub BorType {
569 my ($borrowernumber) = @_;
570 my $dbh = C4::Context->dbh;
571 my $sth = $dbh->prepare(
572 "SELECT * from borrowers
573 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
574 WHERE borrowernumber=?"
576 $sth->execute($borrowernumber);
577 return $sth->fetchrow_hashref;
580 =head2 ReplacementCost
582 $cost = &ReplacementCost($itemnumber);
584 Returns the replacement cost of the item with the given item number.
586 =cut
589 sub ReplacementCost {
590 my ($itemnum) = @_;
591 my $dbh = C4::Context->dbh;
592 my $sth =
593 $dbh->prepare("Select replacementprice from items where itemnumber=?");
594 $sth->execute($itemnum);
596 # FIXME - Use fetchrow_array or a slice.
597 my $data = $sth->fetchrow_hashref;
598 return ( $data->{'replacementprice'} );
601 =head2 GetFine
603 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
605 return the total of fine
607 C<$itemnum> is item number
609 C<$borrowernumber> is the borrowernumber
611 =cut
614 sub GetFine {
615 my ( $itemnum, $borrowernumber ) = @_;
616 my $dbh = C4::Context->dbh();
617 my $query = "SELECT sum(amountoutstanding) FROM accountlines
618 where accounttype like 'F%'
619 AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
620 my $sth = $dbh->prepare($query);
621 $sth->execute( $itemnum, $borrowernumber );
622 my $data = $sth->fetchrow_hashref();
623 return ( $data->{'sum(amountoutstanding)'} );
627 =head2 GetIssuingRules
629 FIXME - This sub should be deprecated and removed.
630 It ignores branch and defaults.
632 $data = &GetIssuingRules($itemtype,$categorycode);
634 Looks up for all issuingrules an item info
636 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
637 from the borrowers and categories tables of the Koha database. Thus,
639 C<$categorycode> contains information about borrowers category
641 C<$data> contains all information about both the borrower and
642 category he or she belongs to.
643 =cut
645 sub GetIssuingRules {
646 warn "GetIssuingRules is deprecated: use GetIssuingRule from C4::Circulation instead.";
647 my ($itemtype,$categorycode)=@_;
648 my $dbh = C4::Context->dbh();
649 my $query=qq|SELECT *
650 FROM issuingrules
651 WHERE issuingrules.itemtype=?
652 AND issuingrules.categorycode=?
654 my $sth = $dbh->prepare($query);
655 # print $query;
656 $sth->execute($itemtype,$categorycode);
657 return $sth->fetchrow_hashref;
661 sub ReplacementCost2 {
662 my ( $itemnum, $borrowernumber ) = @_;
663 my $dbh = C4::Context->dbh();
664 my $query = "SELECT amountoutstanding
665 FROM accountlines
666 WHERE accounttype like 'L'
667 AND amountoutstanding > 0
668 AND itemnumber = ?
669 AND borrowernumber= ?";
670 my $sth = $dbh->prepare($query);
671 $sth->execute( $itemnum, $borrowernumber );
672 my $data = $sth->fetchrow_hashref();
673 return ( $data->{'amountoutstanding'} );
677 =head2 GetNextIdNotify
679 ($result) = &GetNextIdNotify($reference);
681 Returns the new file number
683 C<$result> contains the next file number
685 C<$reference> contains the beggining of file number
687 =cut
689 sub GetNextIdNotify {
690 my ($reference) = @_;
691 my $query = qq|SELECT max(notify_id)
692 FROM accountlines
693 WHERE notify_id like \"$reference%\"
696 # AND borrowernumber=?|;
697 my $dbh = C4::Context->dbh;
698 my $sth = $dbh->prepare($query);
699 $sth->execute();
700 my $result = $sth->fetchrow;
701 my $count;
702 if ( $result eq '' ) {
703 ( $result = $reference . "01" );
705 else {
706 $count = substr( $result, 6 ) + 1;
708 if ( $count < 10 ) {
709 ( $count = "0" . $count );
711 $result = $reference . $count;
713 return $result;
716 =head2 NumberNotifyId
718 (@notify) = &NumberNotifyId($borrowernumber);
720 Returns amount for all file per borrowers
721 C<@notify> array contains all file per borrowers
723 C<$notify_id> contains the file number for the borrower number nad item number
725 =cut
727 sub NumberNotifyId{
728 my ($borrowernumber)=@_;
729 my $dbh = C4::Context->dbh;
730 my $query=qq| SELECT distinct(notify_id)
731 FROM accountlines
732 WHERE borrowernumber=?|;
733 my @notify;
734 my $sth = $dbh->prepare($query);
735 $sth->execute($borrowernumber);
736 while ( my ($numberofnotify) = $sth->fetchrow ) {
737 push( @notify, $numberofnotify );
739 return (@notify);
742 =head2 AmountNotify
744 ($totalnotify) = &AmountNotify($notifyid);
746 Returns amount for all file per borrowers
747 C<$notifyid> is the file number
749 C<$totalnotify> contains amount of a file
751 C<$notify_id> contains the file number for the borrower number and item number
753 =cut
755 sub AmountNotify{
756 my ($notifyid,$borrowernumber)=@_;
757 my $dbh = C4::Context->dbh;
758 my $query=qq| SELECT sum(amountoutstanding)
759 FROM accountlines
760 WHERE notify_id=? AND borrowernumber = ?|;
761 my $sth=$dbh->prepare($query);
762 $sth->execute($notifyid,$borrowernumber);
763 my $totalnotify=$sth->fetchrow;
764 $sth->finish;
765 return ($totalnotify);
769 =head2 GetNotifyId
771 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
773 Returns the file number per borrower and itemnumber
775 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
776 from the items tables of the Koha database. Thus,
778 C<$itemnumber> contains the borrower categorycode
780 C<$notify_id> contains the file number for the borrower number nad item number
782 =cut
784 sub GetNotifyId {
785 my ( $borrowernumber, $itemnumber ) = @_;
786 my $query = qq|SELECT notify_id
787 FROM accountlines
788 WHERE borrowernumber=?
789 AND itemnumber=?
790 AND (accounttype='FU' or accounttype='O')|;
791 my $dbh = C4::Context->dbh;
792 my $sth = $dbh->prepare($query);
793 $sth->execute( $borrowernumber, $itemnumber );
794 my ($notify_id) = $sth->fetchrow;
795 $sth->finish;
796 return ($notify_id);
799 =head2 CreateItemAccountLine
801 () = &CreateItemAccountLine($borrowernumber, $itemnumber, $date, $amount,
802 $description, $accounttype, $amountoutstanding,
803 $timestamp, $notify_id, $level);
805 update the account lines with file number or with file level
807 C<$items> is a reference-to-hash whose keys are all of the fields
808 from the items tables of the Koha database. Thus,
810 C<$itemnumber> contains the item number
812 C<$borrowernumber> contains the borrower number
814 C<$date> contains the date of the day
816 C<$amount> contains item price
818 C<$description> contains the descritpion of accounttype
820 C<$accounttype> contains the account type
822 C<$amountoutstanding> contains the $amountoutstanding
824 C<$timestamp> contains the timestamp with time and the date of the day
826 C<$notify_id> contains the file number
828 C<$level> contains the file level
830 =cut
832 sub CreateItemAccountLine {
833 my (
834 $borrowernumber, $itemnumber, $date, $amount,
835 $description, $accounttype, $amountoutstanding, $timestamp,
836 $notify_id, $level
837 ) = @_;
838 my $dbh = C4::Context->dbh;
839 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
840 my $query = "INSERT into accountlines
841 (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
842 VALUES
843 (?,?,?,?,?,?,?,?,?,?,?)";
845 my $sth = $dbh->prepare($query);
846 $sth->execute(
847 $borrowernumber, $nextaccntno, $itemnumber,
848 $date, $amount, $description,
849 $accounttype, $amountoutstanding, $timestamp,
850 $notify_id, $level
854 =head2 UpdateAccountLines
856 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
858 update the account lines with file number or with file level
860 C<$items> is a reference-to-hash whose keys are all of the fields
861 from the items tables of the Koha database. Thus,
863 C<$itemnumber> contains the item number
865 C<$notify_id> contains the file number
867 C<$notify_level> contains the file level
869 C<$borrowernumber> contains the borrowernumber
871 =cut
873 sub UpdateAccountLines {
874 my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
875 my $query;
876 if ( $notify_id eq '' ) {
877 $query = qq|UPDATE accountlines
878 SET notify_level=?
879 WHERE borrowernumber=? AND itemnumber=?
880 AND (accounttype='FU' or accounttype='O')|;
881 } else {
882 $query = qq|UPDATE accountlines
883 SET notify_id=?, notify_level=?
884 WHERE borrowernumber=?
885 AND itemnumber=?
886 AND (accounttype='FU' or accounttype='O')|;
889 my $sth = C4::Context->dbh->prepare($query);
890 if ( $notify_id eq '' ) {
891 $sth->execute( $notify_level, $borrowernumber, $itemnumber );
892 } else {
893 $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
897 =head2 GetItems
899 ($items) = &GetItems($itemnumber);
901 Returns the list of all delays from overduerules.
903 C<$items> is a reference-to-hash whose keys are all of the fields
904 from the items tables of the Koha database. Thus,
906 C<$itemnumber> contains the borrower categorycode
908 =cut
910 # FIXME: This is a bad function to have here.
911 # Shouldn't it be in C4::Items?
912 # Shouldn't it be called GetItem since you only get 1 row?
913 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
915 sub GetItems {
916 my $itemnumber = shift or return;
917 my $query = qq|SELECT *
918 FROM items
919 WHERE itemnumber=?|;
920 my $sth = C4::Context->dbh->prepare($query);
921 $sth->execute($itemnumber);
922 my ($items) = $sth->fetchrow_hashref;
923 return ($items);
926 =head2 GetOverdueDelays
928 (@delays) = &GetOverdueDelays($categorycode);
930 Returns the list of all delays from overduerules.
932 C<@delays> it's an array contains the three delays from overduerules table
934 C<$categorycode> contains the borrower categorycode
936 =cut
938 sub GetOverdueDelays {
939 my ($category) = @_;
940 my $query = qq|SELECT delay1,delay2,delay3
941 FROM overduerules
942 WHERE categorycode=?|;
943 my $sth = C4::Context->dbh->prepare($query);
944 $sth->execute($category);
945 my (@delays) = $sth->fetchrow_array;
946 return (@delays);
949 =head2 GetBranchcodesWithOverdueRules
951 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
953 returns a list of branch codes for branches with overdue rules defined.
955 =cut
957 sub GetBranchcodesWithOverdueRules {
958 my $dbh = C4::Context->dbh;
959 my $rqoverduebranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode <> ''");
960 $rqoverduebranches->execute;
961 my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
962 return @branches;
965 =head2 CheckAccountLineLevelInfo
967 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
969 Check and Returns the list of all overdue books.
971 C<$exist> contains number of line in accounlines
972 with the same .biblionumber,itemnumber,accounttype,and notify_level
974 C<$borrowernumber> contains the borrower number
976 C<$itemnumber> contains item number
978 C<$accounttype> contains account type
980 C<$notify_level> contains the accountline level
983 =cut
985 sub CheckAccountLineLevelInfo {
986 my ( $borrowernumber, $itemnumber, $level ) = @_;
987 my $dbh = C4::Context->dbh;
988 my $query = qq|SELECT count(*)
989 FROM accountlines
990 WHERE borrowernumber =?
991 AND itemnumber = ?
992 AND notify_level=?|;
993 my $sth = $dbh->prepare($query);
994 $sth->execute( $borrowernumber, $itemnumber, $level );
995 my ($exist) = $sth->fetchrow;
996 return ($exist);
999 =head2 GetOverduerules
1001 ($overduerules) = &GetOverduerules($categorycode);
1003 Returns the value of borrowers (debarred or not) with notify level
1005 C<$overduerules> return value of debbraed field in overduerules table
1007 C<$category> contains the borrower categorycode
1009 C<$notify_level> contains the notify level
1011 =cut
1013 sub GetOverduerules {
1014 my ( $category, $notify_level ) = @_;
1015 my $dbh = C4::Context->dbh;
1016 my $query = qq|SELECT debarred$notify_level
1017 FROM overduerules
1018 WHERE categorycode=?|;
1019 my $sth = $dbh->prepare($query);
1020 $sth->execute($category);
1021 my ($overduerules) = $sth->fetchrow;
1022 return ($overduerules);
1026 =head2 CheckBorrowerDebarred
1028 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1030 Check if the borrowers is already debarred
1032 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1034 C<$borrowernumber> contains the borrower number
1036 =cut
1038 # FIXME: Shouldn't this be in C4::Members?
1039 sub CheckBorrowerDebarred {
1040 my ($borrowernumber) = @_;
1041 my $dbh = C4::Context->dbh;
1042 my $query = qq|
1043 SELECT debarred
1044 FROM borrowers
1045 WHERE borrowernumber=?
1047 my $sth = $dbh->prepare($query);
1048 $sth->execute($borrowernumber);
1049 my ($debarredstatus) = $sth->fetchrow;
1050 return ( $debarredstatus eq '1' ? 1 : 0 );
1053 =head2 UpdateBorrowerDebarred
1055 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
1057 update status of borrowers in borrowers table (field debarred)
1059 C<$borrowernumber> borrower number
1061 =cut
1063 sub UpdateBorrowerDebarred{
1064 my($borrowernumber) = @_;
1065 my $dbh = C4::Context->dbh;
1066 my $query=qq|UPDATE borrowers
1067 SET debarred='1'
1068 WHERE borrowernumber=?
1070 my $sth=$dbh->prepare($query);
1071 $sth->execute($borrowernumber);
1072 $sth->finish;
1073 return 1;
1076 =head2 CheckExistantNotifyid
1078 ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1080 Check and Returns the notify id if exist else return 0.
1082 C<$exist> contains a notify_id
1084 C<$borrowernumber> contains the borrower number
1086 C<$date_due> contains the date of item return
1089 =cut
1091 sub CheckExistantNotifyid {
1092 my ( $borrowernumber, $date_due ) = @_;
1093 my $dbh = C4::Context->dbh;
1094 my $query = qq|SELECT notify_id FROM accountlines
1095 LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1096 WHERE accountlines.borrowernumber =?
1097 AND date_due = ?|;
1098 my $sth = $dbh->prepare($query);
1099 $sth->execute( $borrowernumber, $date_due );
1100 return $sth->fetchrow || 0;
1103 =head2 CheckAccountLineItemInfo
1105 ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1107 Check and Returns the list of all overdue items from the same file number(notify_id).
1109 C<$exist> contains number of line in accounlines
1110 with the same .biblionumber,itemnumber,accounttype,notify_id
1112 C<$borrowernumber> contains the borrower number
1114 C<$itemnumber> contains item number
1116 C<$accounttype> contains account type
1118 C<$notify_id> contains the file number
1120 =cut
1122 sub CheckAccountLineItemInfo {
1123 my ( $borrowernumber, $itemnumber, $accounttype, $notify_id ) = @_;
1124 my $dbh = C4::Context->dbh;
1125 my $query = qq|SELECT count(*) FROM accountlines
1126 WHERE borrowernumber =?
1127 AND itemnumber = ?
1128 AND accounttype= ?
1129 AND notify_id = ?|;
1130 my $sth = $dbh->prepare($query);
1131 $sth->execute( $borrowernumber, $itemnumber, $accounttype, $notify_id );
1132 my ($exist) = $sth->fetchrow;
1133 return ($exist);
1136 =head2 CheckItemNotify
1138 Sql request to check if the document has alreday been notified
1139 this function is not exported, only used with GetOverduesForBranch
1141 =cut
1143 sub CheckItemNotify {
1144 my ($notify_id,$notify_level,$itemnumber) = @_;
1145 my $dbh = C4::Context->dbh;
1146 my $sth = $dbh->prepare("
1147 SELECT COUNT(*)
1148 FROM notifys
1149 WHERE notify_id = ?
1150 AND notify_level = ?
1151 AND itemnumber = ? ");
1152 $sth->execute($notify_id,$notify_level,$itemnumber);
1153 my $notified = $sth->fetchrow;
1154 return ($notified);
1157 =head2 GetOverduesForBranch
1159 Sql request for display all information for branchoverdues.pl
1160 2 possibilities : with or without location .
1161 display is filtered by branch
1163 FIXME: This function should be renamed.
1165 =cut
1167 sub GetOverduesForBranch {
1168 my ( $branch, $location) = @_;
1169 my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype ";
1170 my $dbh = C4::Context->dbh;
1171 my $select = "
1172 SELECT
1173 borrowers.borrowernumber,
1174 borrowers.surname,
1175 borrowers.firstname,
1176 borrowers.phone,
1177 borrowers.email,
1178 biblio.title,
1179 biblio.biblionumber,
1180 issues.date_due,
1181 issues.returndate,
1182 issues.branchcode,
1183 branches.branchname,
1184 items.barcode,
1185 items.itemcallnumber,
1186 items.location,
1187 items.itemnumber,
1188 itemtypes.description,
1189 accountlines.notify_id,
1190 accountlines.notify_level,
1191 accountlines.amountoutstanding
1192 FROM accountlines
1193 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber
1194 AND issues.borrowernumber = accountlines.borrowernumber
1195 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1196 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1197 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1198 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1199 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1200 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1201 WHERE (accountlines.amountoutstanding != '0.000000')
1202 AND (accountlines.accounttype = 'FU' )
1203 AND (issues.branchcode = ? )
1204 AND (issues.date_due < CURDATE())
1206 my @getoverdues;
1207 my $i = 0;
1208 my $sth;
1209 if ($location) {
1210 $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1211 $sth->execute($branch, $location);
1212 } else {
1213 $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1214 $sth->execute($branch);
1216 while ( my $data = $sth->fetchrow_hashref ) {
1217 #check if the document has already been notified
1218 my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1219 if ($countnotify eq '0') {
1220 $getoverdues[$i] = $data;
1221 $i++;
1224 return (@getoverdues);
1228 =head2 AddNotifyLine
1230 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1232 Create a line into notify, if the method is phone, the notification_send_date is implemented to
1234 =cut
1236 sub AddNotifyLine {
1237 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1238 my $dbh = C4::Context->dbh;
1239 if ( $method eq "phone" ) {
1240 my $sth = $dbh->prepare(
1241 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1242 VALUES (?,?,now(),now(),?,?,?)"
1244 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1245 $notifyId );
1247 else {
1248 my $sth = $dbh->prepare(
1249 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1250 VALUES (?,?,now(),?,?,?)"
1252 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1253 $notifyId );
1255 return 1;
1258 =head2 RemoveNotifyLine
1260 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1262 Cancel a notification
1264 =cut
1266 sub RemoveNotifyLine {
1267 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1268 my $dbh = C4::Context->dbh;
1269 my $sth = $dbh->prepare(
1270 "DELETE FROM notifys
1271 WHERE
1272 borrowernumber=?
1273 AND itemnumber=?
1274 AND notify_date=?"
1276 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1277 return 1;
1281 __END__
1283 =head1 AUTHOR
1285 Koha Development Team <http://koha-community.org/>
1287 =cut