Comment out unused variable.
[koha.git] / C4 / Overdues.pm
blob63b0842c524217e60713a38fb82dbb9ac17f802a
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 with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA 02111-1307 USA
21 use strict;
22 use Date::Calc qw/Today/;
23 use Date::Manip qw/UnixDate/;
24 use C4::Circulation;
25 use C4::Context;
26 use C4::Accounts;
27 use C4::Log; # logaction
28 use C4::Debug;
30 use vars qw($VERSION @ISA @EXPORT);
32 BEGIN {
33 # set the version for version checking
34 $VERSION = 3.01;
35 require Exporter;
36 @ISA = qw(Exporter);
37 # subs to rename (and maybe merge some...)
38 push @EXPORT, qw(
39 &CalcFine
40 &Getoverdues
41 &checkoverdues
42 &CheckAccountLineLevelInfo
43 &CheckAccountLineItemInfo
44 &CheckExistantNotifyid
45 &GetNextIdNotify
46 &GetNotifyId
47 &NumberNotifyId
48 &AmountNotify
49 &UpdateAccountLines
50 &UpdateFine
51 &GetOverdueDelays
52 &GetOverduerules
53 &GetFine
54 &CreateItemAccountLine
55 &ReplacementCost2
57 &CheckItemNotify
58 &GetOverduesForBranch
59 &RemoveNotifyLine
60 &AddNotifyLine
62 # subs to remove
63 push @EXPORT, qw(
64 &BorType
67 # check that an equivalent don't exist already before moving
69 # subs to move to Circulation.pm
70 push @EXPORT, qw(
71 &GetIssuesIteminfo
74 # &GetIssuingRules - delete.
75 # use C4::Circulation::GetIssuingRule instead.
77 # subs to move to Members.pm
78 push @EXPORT, qw(
79 &CheckBorrowerDebarred
80 &UpdateBorrowerDebarred
82 # subs to move to Biblio.pm
83 push @EXPORT, qw(
84 &GetItems
85 &ReplacementCost
89 =head1 NAME
91 C4::Circulation::Fines - Koha module dealing with fines
93 =head1 SYNOPSIS
95 use C4::Overdues;
97 =head1 DESCRIPTION
99 This module contains several functions for dealing with fines for
100 overdue items. It is primarily used by the 'misc/fines2.pl' script.
102 =head1 FUNCTIONS
104 =head2 Getoverdues
106 $overdues = Getoverdues( { minimumdays => 1, maximumdays => 30 } );
108 Returns the list of all overdue books, with their itemtype.
110 C<$overdues> is a reference-to-array. Each element is a
111 reference-to-hash whose keys are the fields of the issues table in the
112 Koha database.
114 =cut
117 sub Getoverdues {
118 my $params = shift;
119 my $dbh = C4::Context->dbh;
120 my $statement;
121 if ( C4::Context->preference('item-level_itypes') ) {
122 $statement = "
123 SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode
124 FROM issues
125 LEFT JOIN items USING (itemnumber)
126 WHERE date_due < now()
128 } else {
129 $statement = "
130 SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode
131 FROM issues
132 LEFT JOIN items USING (itemnumber)
133 LEFT JOIN biblioitems USING (biblioitemnumber)
134 WHERE date_due < now()
138 my @bind_parameters;
139 if ( exists $params->{'minimumdays'} and exists $params->{'maximumdays'} ) {
140 $statement .= ' AND TO_DAYS( NOW() )-TO_DAYS( date_due ) BETWEEN ? and ? ';
141 push @bind_parameters, $params->{'minimumdays'}, $params->{'maximumdays'};
142 } elsif ( exists $params->{'minimumdays'} ) {
143 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) > ? ';
144 push @bind_parameters, $params->{'minimumdays'};
145 } elsif ( exists $params->{'maximumdays'} ) {
146 $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ? ';
147 push @bind_parameters, $params->{'maximumdays'};
149 $statement .= 'ORDER BY borrowernumber';
150 my $sth = $dbh->prepare( $statement );
151 $sth->execute( @bind_parameters );
152 return $sth->fetchall_arrayref({});
156 =head2 checkoverdues
158 ( $count, $overdueitems )=checkoverdues( $borrowernumber, $dbh );
160 Not exported
162 =cut
164 sub checkoverdues {
166 # From Main.pm, modified to return a list of overdueitems, in addition to a count
167 #checks whether a borrower has overdue items
168 my ( $borrowernumber, $dbh ) = @_;
169 my @datearr = localtime;
170 my $today =
171 ( $datearr[5] + 1900 ) . "-" . ( $datearr[4] + 1 ) . "-" . $datearr[3];
172 my @overdueitems;
173 my $count = 0;
174 my $sth = $dbh->prepare(
175 "SELECT * FROM issues
176 LEFT JOIN items ON issues.itemnumber = items.itemnumber
177 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
178 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
179 WHERE issues.borrowernumber = ?
180 AND issues.date_due < ?"
182 $sth->execute( $borrowernumber, $today );
183 while ( my $data = $sth->fetchrow_hashref ) {
184 push( @overdueitems, $data );
185 $count++;
187 $sth->finish;
188 return ( $count, \@overdueitems );
191 =head2 CalcFine
193 ($amount, $chargename, $daycount, $daycounttotal) =
194 &CalcFine($item, $categorycode, $branch, $days_overdue, $description, $start_date, $end_date );
196 Calculates the fine for a book.
198 The issuingrules table in the Koha database is a fine matrix, listing
199 the penalties for each type of patron for each type of item and each branch (e.g., the
200 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
201 members might get a longer grace period between the first and second
202 reminders that a book is overdue).
205 C<$item> is an item object (hashref).
207 C<$categorycode> is the category code (string) of the patron who currently has
208 the book.
210 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
212 C<$days_overdue> is the number of days elapsed since the book's due date.
213 NOTE: supplying days_overdue is deprecated.
215 C<$start_date> & C<$end_date> are C4::Dates objects
216 defining the date range over which to determine the fine.
217 Note that if these are defined, we ignore C<$difference> and C<$dues> ,
218 but retain these for backwards-comptibility with extant fines scripts.
220 Fines scripts should just supply the date range over which to calculate the fine.
222 C<&CalcFine> returns four values:
224 C<$amount> is the fine owed by the patron (see above).
226 C<$chargename> is the chargename field from the applicable record in
227 the categoryitem table, whatever that is.
229 C<$daycount> is the number of days between start and end dates, Calendar adjusted (where needed),
230 minus any applicable grace period.
232 C<$daycounttotal> is C<$daycount> without consideration of grace period.
234 FIXME - What is chargename supposed to be ?
236 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
237 or "Final Notice". But CalcFine never defined any value.
239 =cut
241 sub CalcFine {
242 my ( $item, $bortype, $branchcode, $difference ,$dues , $start_date, $end_date ) = @_;
243 $debug and warn sprintf("CalcFine(%s, %s, %s, %s, %s, %s, %s)",
244 ($item ? '{item}' : 'UNDEF'),
245 ($bortype || 'UNDEF'),
246 ($branchcode || 'UNDEF'),
247 ($difference || 'UNDEF'),
248 ($dues || 'UNDEF'),
249 ($start_date ? ($start_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF'),
250 ( $end_date ? ( $end_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF')
252 my $dbh = C4::Context->dbh;
253 my $amount = 0;
254 my $daystocharge;
255 # get issuingrules (fines part will be used)
256 $debug and warn sprintf("CalcFine calling GetIssuingRule(%s, %s, %s)", $bortype, $item->{'itemtype'}, $branchcode);
257 my $data = C4::Circulation::GetIssuingRule($bortype, $item->{'itemtype'}, $branchcode);
258 if($difference) {
259 # if $difference is supplied, the difference has already been calculated, but we still need to adjust for the calendar.
260 # use copy-pasted functions from calendar module. (deprecated -- these functions will be removed from C4::Overdues ).
261 my $countspecialday = &GetSpecialHolidays($dues,$item->{itemnumber});
262 my $countrepeatableday = &GetRepeatableHolidays($dues,$item->{itemnumber},$difference);
263 my $countalldayclosed = $countspecialday + $countrepeatableday;
264 $daystocharge = $difference - $countalldayclosed;
265 } else {
266 # if $difference is not supplied, we have C4::Dates objects giving us the date range, and we use the calendar module.
267 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
268 my $calendar = C4::Calendar->new( branchcode => $branchcode );
269 $daystocharge = $calendar->daysBetween( $start_date, $end_date );
270 } else {
271 $daystocharge = Date_to_Days(split('-',$end_date->output('iso'))) - Date_to_Days(split('-',$start_date->output('iso')));
274 # correct for grace period.
275 my $days_minus_grace = $daystocharge - $data->{'firstremind'};
276 if ($data->{'chargeperiod'} > 0 && $days_minus_grace > 0 ) {
277 $amount = int($days_minus_grace / $data->{'chargeperiod'}) * $data->{'fine'};
278 } else {
279 # a zero (or null) chargeperiod means no charge.
281 $amount = C4::Context->preference('maxFine') if(C4::Context->preference('maxFine') && ( $amount > C4::Context->preference('maxFine')));
282 $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
283 return ($amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
284 # FIXME: chargename is NEVER populated anywhere.
288 =head2 GetSpecialHolidays
290 &GetSpecialHolidays($date_dues,$itemnumber);
292 return number of special days between date of the day and date due
294 C<$date_dues> is the envisaged date of book return.
296 C<$itemnumber> is the book's item number.
298 =cut
300 sub GetSpecialHolidays {
301 my ($date_dues,$itemnumber) = @_;
302 # calcul the today date
303 my $today = join "-", &Today();
305 # return the holdingbranch
306 my $iteminfo=GetIssuesIteminfo($itemnumber);
307 # use sql request to find all date between date_due and today
308 my $dbh = C4::Context->dbh;
309 my $query=qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d')as date
310 FROM `special_holidays`
311 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
312 AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
313 AND branchcode=?
315 my @result=GetWdayFromItemnumber($itemnumber);
316 my @result_date;
317 my $wday;
318 my $dateinsec;
319 my $sth = $dbh->prepare($query);
320 $sth->execute($date_dues,$today,$iteminfo->{'branchcode'});
322 while ( my $special_date=$sth->fetchrow_hashref){
323 push (@result_date,$special_date);
326 my $specialdaycount=scalar(@result_date);
328 for (my $i=0;$i<scalar(@result_date);$i++){
329 $dateinsec=UnixDate($result_date[$i]->{'date'},"%o");
330 (undef,undef,undef,undef,undef,undef,$wday,undef,undef) =localtime($dateinsec);
331 for (my $j=0;$j<scalar(@result);$j++){
332 if ($wday == ($result[$j]->{'weekday'})){
333 $specialdaycount --;
338 return $specialdaycount;
341 =head2 GetRepeatableHolidays
343 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
345 return number of day closed between date of the day and date due
347 C<$date_dues> is the envisaged date of book return.
349 C<$itemnumber> is item number.
351 C<$difference> numbers of between day date of the day and date due
353 =cut
355 sub GetRepeatableHolidays{
356 my ($date_dues,$itemnumber,$difference) = @_;
357 my $dateinsec=UnixDate($date_dues,"%o");
358 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime($dateinsec);
359 my @result=GetWdayFromItemnumber($itemnumber);
360 my @dayclosedcount;
361 my $j;
363 for (my $i=0;$i<scalar(@result);$i++){
364 my $k=$wday;
366 for ( $j=0;$j<$difference;$j++){
367 if ($result[$i]->{'weekday'} == $k)
369 push ( @dayclosedcount ,$k);
371 $k++;
372 ($k=0) if($k eq 7);
375 return scalar(@dayclosedcount);
379 =head2 GetWayFromItemnumber
381 &Getwdayfromitemnumber($itemnumber);
383 return the different week day from repeatable_holidays table
385 C<$itemnumber> is item number.
387 =cut
389 sub GetWdayFromItemnumber{
390 my($itemnumber)=@_;
391 my $iteminfo=GetIssuesIteminfo($itemnumber);
392 my @result;
393 my $dbh = C4::Context->dbh;
394 my $query = qq|SELECT weekday
395 FROM repeatable_holidays
396 WHERE branchcode=?
398 my $sth = $dbh->prepare($query);
399 # print $query;
401 $sth->execute($iteminfo->{'branchcode'});
402 while ( my $weekday=$sth->fetchrow_hashref){
403 push (@result,$weekday);
405 return @result;
409 =head2 GetIssuesIteminfo
411 &GetIssuesIteminfo($itemnumber);
413 return all data from issues about item
415 C<$itemnumber> is item number.
417 =cut
419 sub GetIssuesIteminfo{
420 my($itemnumber)=@_;
421 my $dbh = C4::Context->dbh;
422 my $query = qq|SELECT *
423 FROM issues
424 WHERE itemnumber=?
426 my $sth = $dbh->prepare($query);
427 $sth->execute($itemnumber);
428 my ($issuesinfo)=$sth->fetchrow_hashref;
429 return $issuesinfo;
433 =head2 UpdateFine
435 &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
437 (Note: the following is mostly conjecture and guesswork.)
439 Updates the fine owed on an overdue book.
441 C<$itemnumber> is the book's item number.
443 C<$borrowernumber> is the borrower number of the patron who currently
444 has the book on loan.
446 C<$amount> is the current amount owed by the patron.
448 C<$type> will be used in the description of the fine.
450 C<$description> is a string that must be present in the description of
451 the fine. I think this is expected to be a date in DD/MM/YYYY format.
453 C<&UpdateFine> looks up the amount currently owed on the given item
454 and sets it to C<$amount>, creating, if necessary, a new entry in the
455 accountlines table of the Koha database.
457 =cut
460 # Question: Why should the caller have to
461 # specify both the item number and the borrower number? A book can't
462 # be on loan to two different people, so the item number should be
463 # sufficient.
465 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
467 sub UpdateFine {
468 my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
469 $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
470 my $dbh = C4::Context->dbh;
471 # FIXME - What exactly is this query supposed to do? It looks up an
472 # entry in accountlines that matches the given item and borrower
473 # numbers, where the description contains $due, and where the
474 # account type has one of several values, but what does this _mean_?
475 # Does it look up existing fines for this item?
476 # FIXME - What are these various account types? ("FU", "O", "F", "M")
477 # "L" is LOST item
478 # "A" is Account Management Fee
479 # "N" is New Card
480 # "M" is Sundry
481 # "O" is Overdue ??
482 # "F" is Fine ??
483 # "FU" is Fine UPDATE??
484 # "Pay" is Payment
485 # "REF" is Cash Refund
486 my $sth = $dbh->prepare(
487 "SELECT * FROM accountlines
488 WHERE itemnumber=?
489 AND borrowernumber=?
490 AND accounttype IN ('FU','O','F','M')
491 AND description like ? "
493 $sth->execute( $itemnum, $borrowernumber, "%$due%" );
495 if ( my $data = $sth->fetchrow_hashref ) {
497 # we're updating an existing fine. Only modify if we're adding to the charge.
498 # Note that in the current implementation, you cannot pay against an accruing fine
499 # (i.e. , of accounttype 'FU'). Doing so will break accrual.
500 if ( $data->{'amount'} != $amount ) {
501 my $diff = $amount - $data->{'amount'};
502 $diff = 0 if ( $data->{amount} > $amount);
503 my $out = $data->{'amountoutstanding'} + $diff;
504 my $query = "
505 UPDATE accountlines
506 SET date=now(), amount=?, amountoutstanding=?,
507 lastincrement=?, accounttype='FU'
508 WHERE borrowernumber=?
509 AND itemnumber=?
510 AND accounttype IN ('FU','O')
511 AND description LIKE ?
512 LIMIT 1 ";
513 my $sth2 = $dbh->prepare($query);
514 # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
515 # LIMIT 1 added to prevent multiple affected lines
516 # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.
517 # But actually, we should just have a regular autoincrementing PK and forget accountline,
518 # including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
519 # FIXME: Why only 2 account types here?
520 $debug and print STDERR "UpdateFine query: $query\n" .
521 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
522 $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
523 } else {
524 # print "no update needed $data->{'amount'}"
526 } else {
527 my $sth4 = $dbh->prepare(
528 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
530 $sth4->execute($itemnum);
531 my $title = $sth4->fetchrow;
533 # # print "not in account";
534 # my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
535 # $sth3->execute;
537 # # FIXME - Make $accountno a scalar.
538 # my @accountno = $sth3->fetchrow_array;
539 # $sth3->finish;
540 # $accountno[0]++;
541 # begin transaction
542 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
543 my $desc = ($type ? "$type " : '') . "$title $due"; # FIXEDME, avoid whitespace prefix on empty $type
544 my $query = "INSERT INTO accountlines
545 (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
546 VALUES (?,?,now(),?,?,'FU',?,?,?)";
547 my $sth2 = $dbh->prepare($query);
548 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
549 $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
551 # logging action
552 &logaction(
553 "FINES",
554 $type,
555 $borrowernumber,
556 "due=".$due." amount=".$amount." itemnumber=".$itemnum
557 ) if C4::Context->preference("FinesLog");
560 =head2 BorType
562 $borrower = &BorType($borrowernumber);
564 Looks up a patron by borrower number.
566 C<$borrower> is a reference-to-hash whose keys are all of the fields
567 from the borrowers and categories tables of the Koha database. Thus,
568 C<$borrower> contains all information about both the borrower and
569 category he or she belongs to.
571 =cut
574 sub BorType {
575 my ($borrowernumber) = @_;
576 my $dbh = C4::Context->dbh;
577 my $sth = $dbh->prepare(
578 "SELECT * from borrowers
579 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
580 WHERE borrowernumber=?"
582 $sth->execute($borrowernumber);
583 my $data = $sth->fetchrow_hashref;
584 $sth->finish;
585 return ($data);
588 =head2 ReplacementCost
590 $cost = &ReplacementCost($itemnumber);
592 Returns the replacement cost of the item with the given item number.
594 =cut
597 sub ReplacementCost {
598 my ($itemnum) = @_;
599 my $dbh = C4::Context->dbh;
600 my $sth =
601 $dbh->prepare("Select replacementprice from items where itemnumber=?");
602 $sth->execute($itemnum);
604 # FIXME - Use fetchrow_array or something.
605 my $data = $sth->fetchrow_hashref;
606 $sth->finish;
607 return ( $data->{'replacementprice'} );
610 =head2 GetFine
612 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
614 return the total of fine
616 C<$itemnum> is item number
618 C<$borrowernumber> is the borrowernumber
620 =cut
623 sub GetFine {
624 my ( $itemnum, $borrowernumber ) = @_;
625 my $dbh = C4::Context->dbh();
626 my $query = "SELECT sum(amountoutstanding) FROM accountlines
627 where accounttype like 'F%'
628 AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
629 my $sth = $dbh->prepare($query);
630 $sth->execute( $itemnum, $borrowernumber );
631 my $data = $sth->fetchrow_hashref();
632 return ( $data->{'sum(amountoutstanding)'} );
636 =head2 GetIssuingRules
638 FIXME - This sub should be deprecated and removed.
639 It ignores branch and defaults.
641 $data = &GetIssuingRules($itemtype,$categorycode);
643 Looks up for all issuingrules an item info
645 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
646 from the borrowers and categories tables of the Koha database. Thus,
648 C<$categorycode> contains information about borrowers category
650 C<$data> contains all information about both the borrower and
651 category he or she belongs to.
652 =cut
654 sub GetIssuingRules {
655 warn "GetIssuingRules is deprecated: use GetIssuingRule from C4::Circulation instead.";
656 my ($itemtype,$categorycode)=@_;
657 my $dbh = C4::Context->dbh();
658 my $query=qq|SELECT *
659 FROM issuingrules
660 WHERE issuingrules.itemtype=?
661 AND issuingrules.categorycode=?
663 my $sth = $dbh->prepare($query);
664 # print $query;
665 $sth->execute($itemtype,$categorycode);
666 return $sth->fetchrow_hashref;
670 sub ReplacementCost2 {
671 my ( $itemnum, $borrowernumber ) = @_;
672 my $dbh = C4::Context->dbh();
673 my $query = "SELECT amountoutstanding
674 FROM accountlines
675 WHERE accounttype like 'L'
676 AND amountoutstanding > 0
677 AND itemnumber = ?
678 AND borrowernumber= ?";
679 my $sth = $dbh->prepare($query);
680 $sth->execute( $itemnum, $borrowernumber );
681 my $data = $sth->fetchrow_hashref();
682 return ( $data->{'amountoutstanding'} );
686 =head2 GetNextIdNotify
688 ($result) = &GetNextIdNotify($reference);
690 Returns the new file number
692 C<$result> contains the next file number
694 C<$reference> contains the beggining of file number
696 =cut
700 sub GetNextIdNotify {
701 my ($reference)=@_;
702 my $query=qq|SELECT max(notify_id)
703 FROM accountlines
704 WHERE notify_id like \"$reference%\"
706 # AND borrowernumber=?|;
707 my $dbh = C4::Context->dbh;
708 my $sth=$dbh->prepare($query);
709 $sth->execute();
710 my $result=$sth->fetchrow;
711 $sth->finish;
712 my $count;
713 if ($result eq '')
715 ($result=$reference."01") ;
716 }else
718 $count=substr($result,6)+1;
720 if($count<10){
721 ($count = "0".$count);
723 $result=$reference.$count;
725 return $result;
729 =head2 NumberNotifyId
731 (@notify) = &NumberNotifyId($borrowernumber);
733 Returns amount for all file per borrowers
734 C<@notify> array contains all file per borrowers
736 C<$notify_id> contains the file number for the borrower number nad item number
738 =cut
740 sub NumberNotifyId{
741 my ($borrowernumber)=@_;
742 my $dbh = C4::Context->dbh;
743 my $query=qq| SELECT distinct(notify_id)
744 FROM accountlines
745 WHERE borrowernumber=?|;
746 my @notify;
747 my $sth=$dbh->prepare($query);
748 $sth->execute($borrowernumber);
749 while ( my ($numberofnotify)=$sth->fetchrow){
750 push (@notify,$numberofnotify);
752 $sth->finish;
754 return (@notify);
758 =head2 AmountNotify
760 ($totalnotify) = &AmountNotify($notifyid);
762 Returns amount for all file per borrowers
763 C<$notifyid> is the file number
765 C<$totalnotify> contains amount of a file
767 C<$notify_id> contains the file number for the borrower number and item number
769 =cut
771 sub AmountNotify{
772 my ($notifyid,$borrowernumber)=@_;
773 my $dbh = C4::Context->dbh;
774 my $query=qq| SELECT sum(amountoutstanding)
775 FROM accountlines
776 WHERE notify_id=? AND borrowernumber = ?|;
777 my $sth=$dbh->prepare($query);
778 $sth->execute($notifyid,$borrowernumber);
779 my $totalnotify=$sth->fetchrow;
780 $sth->finish;
781 return ($totalnotify);
785 =head2 GetNotifyId
787 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
789 Returns the file number per borrower and itemnumber
791 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
792 from the items tables of the Koha database. Thus,
794 C<$itemnumber> contains the borrower categorycode
796 C<$notify_id> contains the file number for the borrower number nad item number
798 =cut
800 sub GetNotifyId {
801 my ($borrowernumber,$itemnumber)=@_;
802 my $query=qq|SELECT notify_id
803 FROM accountlines
804 WHERE borrowernumber=?
805 AND itemnumber=?
806 AND (accounttype='FU' or accounttype='O')|;
807 my $dbh = C4::Context->dbh;
808 my $sth=$dbh->prepare($query);
809 $sth->execute($borrowernumber,$itemnumber);
810 my ($notify_id)=$sth->fetchrow;
811 $sth->finish;
812 return ($notify_id);
816 =head2 CreateItemAccountLine
818 () = &CreateItemAccountLine($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
820 update the account lines with file number or with file level
822 C<$items> is a reference-to-hash whose keys are all of the fields
823 from the items tables of the Koha database. Thus,
825 C<$itemnumber> contains the item number
827 C<$borrowernumber> contains the borrower number
829 C<$date> contains the date of the day
831 C<$amount> contains item price
833 C<$description> contains the descritpion of accounttype
835 C<$accounttype> contains the account type
837 C<$amountoutstanding> contains the $amountoutstanding
839 C<$timestamp> contains the timestamp with time and the date of the day
841 C<$notify_id> contains the file number
843 C<$level> contains the file level
846 =cut
848 sub CreateItemAccountLine {
849 my ($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level)=@_;
850 my $dbh = C4::Context->dbh;
851 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
852 my $query= "INSERT into accountlines
853 (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
854 VALUES
855 (?,?,?,?,?,?,?,?,?,?,?)";
858 my $sth=$dbh->prepare($query);
859 $sth->execute($borrowernumber,$nextaccntno,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
860 $sth->finish;
863 =head2 UpdateAccountLines
865 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
867 update the account lines with file number or with file level
869 C<$items> is a reference-to-hash whose keys are all of the fields
870 from the items tables of the Koha database. Thus,
872 C<$itemnumber> contains the item number
874 C<$notify_id> contains the file number
876 C<$notify_level> contains the file level
878 C<$borrowernumber> contains the borrowernumber
880 =cut
882 sub UpdateAccountLines {
883 my ($notify_id,$notify_level,$borrowernumber,$itemnumber)=@_;
884 my $query;
885 if ($notify_id eq '')
888 $query=qq|UPDATE accountlines
889 SET notify_level=?
890 WHERE borrowernumber=? AND itemnumber=?
891 AND (accounttype='FU' or accounttype='O')|;
892 }else
894 $query=qq|UPDATE accountlines
895 SET notify_id=?, notify_level=?
896 WHERE borrowernumber=?
897 AND itemnumber=?
898 AND (accounttype='FU' or accounttype='O')|;
900 my $dbh = C4::Context->dbh;
901 my $sth=$dbh->prepare($query);
903 if ($notify_id eq '')
905 $sth->execute($notify_level,$borrowernumber,$itemnumber);
906 }else
908 $sth->execute($notify_id,$notify_level,$borrowernumber,$itemnumber);
910 $sth->finish;
915 =head2 GetItems
917 ($items) = &GetItems($itemnumber);
919 Returns the list of all delays from overduerules.
921 C<$items> is a reference-to-hash whose keys are all of the fields
922 from the items tables of the Koha database. Thus,
924 C<$itemnumber> contains the borrower categorycode
926 =cut
928 sub GetItems {
929 my($itemnumber) = @_;
930 my $query=qq|SELECT *
931 FROM items
932 WHERE itemnumber=?|;
933 my $dbh = C4::Context->dbh;
934 my $sth=$dbh->prepare($query);
935 $sth->execute($itemnumber);
936 my ($items)=$sth->fetchrow_hashref;
937 $sth->finish;
938 return($items);
941 =head2 GetOverdueDelays
943 (@delays) = &GetOverdueDelays($categorycode);
945 Returns the list of all delays from overduerules.
947 C<@delays> it's an array contains the three delays from overduerules table
949 C<$categorycode> contains the borrower categorycode
951 =cut
953 sub GetOverdueDelays {
954 my($category) = @_;
955 my $dbh = C4::Context->dbh;
956 my $query=qq|SELECT delay1,delay2,delay3
957 FROM overduerules
958 WHERE categorycode=?|;
959 my $sth=$dbh->prepare($query);
960 $sth->execute($category);
961 my (@delays)=$sth->fetchrow_array;
962 $sth->finish;
963 return(@delays);
966 =head2 GetBranchcodesWithOverdueRules
968 =over 4
970 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
972 returns a list of branch codes for branches with overdue rules defined.
974 =back
976 =cut
978 sub GetBranchcodesWithOverdueRules {
979 my $dbh = C4::Context->dbh;
980 my $rqoverduebranches = $dbh->prepare("SELECT DISTINCT branchcode FROM overduerules WHERE delay1 IS NOT NULL AND branchcode <> ''");
981 $rqoverduebranches->execute;
982 my @branches = map { shift @$_ } @{ $rqoverduebranches->fetchall_arrayref };
983 $rqoverduebranches->finish;
984 return @branches;
987 =head2 CheckAccountLineLevelInfo
989 ($exist) = &CheckAccountLineLevelInfo($borrowernumber,$itemnumber,$accounttype,notify_level);
991 Check and Returns the list of all overdue books.
993 C<$exist> contains number of line in accounlines
994 with the same .biblionumber,itemnumber,accounttype,and notify_level
996 C<$borrowernumber> contains the borrower number
998 C<$itemnumber> contains item number
1000 C<$accounttype> contains account type
1002 C<$notify_level> contains the accountline level
1005 =cut
1007 sub CheckAccountLineLevelInfo {
1008 my($borrowernumber,$itemnumber,$level) = @_;
1009 my $dbh = C4::Context->dbh;
1010 my $query= qq|SELECT count(*)
1011 FROM accountlines
1012 WHERE borrowernumber =?
1013 AND itemnumber = ?
1014 AND notify_level=?|;
1015 my $sth=$dbh->prepare($query);
1016 $sth->execute($borrowernumber,$itemnumber,$level);
1017 my ($exist)=$sth->fetchrow;
1018 $sth->finish;
1019 return($exist);
1022 =head2 GetOverduerules
1024 ($overduerules) = &GetOverduerules($categorycode);
1026 Returns the value of borrowers (debarred or not) with notify level
1028 C<$overduerules> return value of debbraed field in overduerules table
1030 C<$category> contains the borrower categorycode
1032 C<$notify_level> contains the notify level
1034 =cut
1036 sub GetOverduerules{
1037 my($category,$notify_level) = @_;
1038 my $dbh = C4::Context->dbh;
1039 my $query=qq|SELECT debarred$notify_level
1040 FROM overduerules
1041 WHERE categorycode=?|;
1042 my $sth=$dbh->prepare($query);
1043 $sth->execute($category);
1044 my ($overduerules)=$sth->fetchrow;
1045 $sth->finish;
1046 return($overduerules);
1050 =head2 CheckBorrowerDebarred
1052 ($debarredstatus) = &CheckBorrowerDebarred($borrowernumber);
1054 Check if the borrowers is already debarred
1056 C<$debarredstatus> return 0 for not debarred and return 1 for debarred
1058 C<$borrowernumber> contains the borrower number
1060 =cut
1063 sub CheckBorrowerDebarred{
1064 my($borrowernumber) = @_;
1065 my $dbh = C4::Context->dbh;
1066 my $query=qq|SELECT debarred
1067 FROM borrowers
1068 WHERE borrowernumber=?
1070 my $sth=$dbh->prepare($query);
1071 $sth->execute($borrowernumber);
1072 my ($debarredstatus)=$sth->fetchrow;
1073 $sth->finish;
1074 if ($debarredstatus eq '1'){
1075 return(1);}
1076 else{
1077 return(0);
1081 =head2 UpdateBorrowerDebarred
1083 ($borrowerstatut) = &UpdateBorrowerDebarred($borrowernumber);
1085 update status of borrowers in borrowers table (field debarred)
1087 C<$borrowernumber> borrower number
1089 =cut
1091 sub UpdateBorrowerDebarred{
1092 my($borrowernumber) = @_;
1093 my $dbh = C4::Context->dbh;
1094 my $query=qq|UPDATE borrowers
1095 SET debarred='1'
1096 WHERE borrowernumber=?
1098 my $sth=$dbh->prepare($query);
1099 $sth->execute($borrowernumber);
1100 $sth->finish;
1101 return 1;
1104 =head2 CheckExistantNotifyid
1106 ($exist) = &CheckExistantNotifyid($borrowernumber,$itemnumber,$accounttype,$notify_id);
1108 Check and Returns the notify id if exist else return 0.
1110 C<$exist> contains a notify_id
1112 C<$borrowernumber> contains the borrower number
1114 C<$date_due> contains the date of item return
1117 =cut
1119 sub CheckExistantNotifyid {
1120 my($borrowernumber,$date_due) = @_;
1121 my $dbh = C4::Context->dbh;
1122 my $query = qq|SELECT notify_id FROM accountlines
1123 LEFT JOIN issues ON issues.itemnumber= accountlines.itemnumber
1124 WHERE accountlines.borrowernumber =?
1125 AND date_due = ?|;
1126 my $sth=$dbh->prepare($query);
1127 $sth->execute($borrowernumber,$date_due);
1128 my ($exist)=$sth->fetchrow;
1129 $sth->finish;
1130 if ($exist eq '')
1132 return(0);
1133 }else
1135 return($exist);
1139 =head2 CheckAccountLineItemInfo
1141 ($exist) = &CheckAccountLineItemInfo($borrowernumber,$itemnumber,$accounttype,$notify_id);
1143 Check and Returns the list of all overdue items from the same file number(notify_id).
1145 C<$exist> contains number of line in accounlines
1146 with the same .biblionumber,itemnumber,accounttype,notify_id
1148 C<$borrowernumber> contains the borrower number
1150 C<$itemnumber> contains item number
1152 C<$accounttype> contains account type
1154 C<$notify_id> contains the file number
1156 =cut
1158 sub CheckAccountLineItemInfo {
1159 my($borrowernumber,$itemnumber,$accounttype,$notify_id) = @_;
1160 my $dbh = C4::Context->dbh;
1161 my $query = qq|SELECT count(*) FROM accountlines
1162 WHERE borrowernumber =?
1163 AND itemnumber = ?
1164 AND accounttype= ?
1165 AND notify_id = ?|;
1166 my $sth=$dbh->prepare($query);
1167 $sth->execute($borrowernumber,$itemnumber,$accounttype,$notify_id);
1168 my ($exist)=$sth->fetchrow;
1169 $sth->finish;
1170 return($exist);
1173 =head2 CheckItemNotify
1175 Sql request to check if the document has alreday been notified
1176 this function is not exported, only used with GetOverduesForBranch
1178 =cut
1180 sub CheckItemNotify {
1181 my ($notify_id,$notify_level,$itemnumber) = @_;
1182 my $dbh = C4::Context->dbh;
1183 my $sth = $dbh->prepare("
1184 SELECT COUNT(*) FROM notifys
1185 WHERE notify_id = ?
1186 AND notify_level = ?
1187 AND itemnumber = ? ");
1188 $sth->execute($notify_id,$notify_level,$itemnumber);
1189 my $notified = $sth->fetchrow;
1190 $sth->finish;
1191 return ($notified);
1194 =head2 GetOverduesForBranch
1196 Sql request for display all information for branchoverdues.pl
1197 2 possibilities : with or without location .
1198 display is filtered by branch
1200 =cut
1202 sub GetOverduesForBranch {
1203 my ( $branch, $location) = @_;
1204 my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype ";
1205 if ( not $location ) {
1206 my $dbh = C4::Context->dbh;
1207 my $sth = $dbh->prepare("
1208 SELECT
1209 borrowers.surname,
1210 borrowers.firstname,
1211 biblio.title,
1212 itemtypes.description,
1213 issues.date_due,
1214 issues.returndate,
1215 branches.branchname,
1216 items.barcode,
1217 borrowers.phone,
1218 borrowers.email,
1219 items.itemcallnumber,
1220 borrowers.borrowernumber,
1221 items.itemnumber,
1222 biblio.biblionumber,
1223 issues.branchcode,
1224 accountlines.notify_id,
1225 accountlines.notify_level,
1226 items.location,
1227 accountlines.amountoutstanding
1228 FROM accountlines
1229 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber AND issues.borrowernumber = accountlines.borrowernumber
1230 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1231 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1232 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1233 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=items.biblioitemnumber
1234 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1235 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1236 WHERE ( accountlines.amountoutstanding != '0.000000')
1237 AND ( accountlines.accounttype = 'FU')
1238 AND (issues.branchcode = ?)
1239 AND (issues.date_due <= NOW())
1240 ORDER BY borrowers.surname
1242 $sth->execute($branch);
1243 my @getoverdues;
1244 my $i = 0;
1245 while ( my $data = $sth->fetchrow_hashref ) {
1246 #check if the document has already been notified
1247 my $countnotify = CheckItemNotify($data->{'notify_id'},$data->{'notify_level'},$data->{'itemnumber'});
1248 if ($countnotify eq '0'){
1249 $getoverdues[$i] = $data;
1250 $i++;
1253 return (@getoverdues);
1254 $sth->finish;
1256 else {
1257 my $dbh = C4::Context->dbh;
1258 my $sth = $dbh->prepare( "
1259 SELECT borrowers.surname,
1260 borrowers.firstname,
1261 biblio.title,
1262 itemtypes.description,
1263 issues.date_due,
1264 issues.returndate,
1265 branches.branchname,
1266 items.barcode,
1267 borrowers.phone,
1268 borrowers.email,
1269 items.itemcallnumber,
1270 borrowers.borrowernumber,
1271 items.itemnumber,
1272 biblio.biblionumber,
1273 issues.branchcode,
1274 accountlines.notify_id,
1275 accountlines.notify_level,
1276 items.location,
1277 accountlines.amountoutstanding
1278 FROM accountlines
1279 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber AND issues.borrowernumber = accountlines.borrowernumber
1280 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1281 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1282 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1283 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=items.biblioitemnumber
1284 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1285 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1286 WHERE ( accountlines.amountoutstanding != '0.000000')
1287 AND ( accountlines.accounttype = 'FU')
1288 AND (issues.branchcode = ? AND items.location = ?)
1289 AND (issues.date_due <= NOW())
1290 ORDER BY borrowers.surname
1291 " );
1292 $sth->execute( $branch, $location);
1293 my @getoverdues;
1294 my $i = 0;
1295 while ( my $data = $sth->fetchrow_hashref ) {
1296 #check if the document has already been notified
1297 my $countnotify = CheckItemNotify($data->{'notify_id'},$data->{'notify_level'},$data->{'itemnumber'});
1298 if ($countnotify eq '0'){
1299 $getoverdues[$i] = $data;
1300 $i++;
1303 $sth->finish;
1304 return (@getoverdues);
1309 =head2 AddNotifyLine
1311 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1313 Creat a line into notify, if the method is phone, the notification_send_date is implemented to
1315 =cut
1317 sub AddNotifyLine {
1318 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1319 if ( $method eq "phone" ) {
1320 my $dbh = C4::Context->dbh;
1321 my $sth = $dbh->prepare(
1322 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1323 VALUES (?,?,now(),now(),?,?,?)"
1325 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1326 $notifyId );
1327 $sth->finish;
1329 else {
1330 my $dbh = C4::Context->dbh;
1331 my $sth = $dbh->prepare(
1332 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1333 VALUES (?,?,now(),?,?,?)"
1335 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1336 $notifyId );
1337 $sth->finish;
1339 return 1;
1342 =head2 RemoveNotifyLine
1344 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1346 Cancel a notification
1348 =cut
1350 sub RemoveNotifyLine {
1351 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1352 my $dbh = C4::Context->dbh;
1353 my $sth = $dbh->prepare(
1354 "DELETE FROM notifys
1355 WHERE
1356 borrowernumber=?
1357 AND itemnumber=?
1358 AND notify_date=?"
1360 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1361 $sth->finish;
1362 return 1;
1366 __END__
1368 =head1 AUTHOR
1370 Koha Developement team <info@koha.org>
1372 =cut