MT2582: Fix user deletion without permission
[koha.git] / C4 / Overdues.pm
blob7f59b9bed4cc46544bc11e6fbef778c2d956e0b2
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) =
184 &CalcFine($item, $categorycode, $branch, $days_overdue, $description, $start_date, $end_date );
186 Calculates the fine for a book.
188 The issuingrules table in the Koha database is a fine matrix, listing
189 the penalties for each type of patron for each type of item and each branch (e.g., the
190 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
191 members might get a longer grace period between the first and second
192 reminders that a book is overdue).
195 C<$item> is an item object (hashref).
197 C<$categorycode> is the category code (string) of the patron who currently has
198 the book.
200 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
202 C<$days_overdue> is the number of days elapsed since the book's due date.
203 NOTE: supplying days_overdue is deprecated.
205 C<$start_date> & C<$end_date> are C4::Dates objects
206 defining the date range over which to determine the fine.
207 Note that if these are defined, we ignore C<$difference> and C<$dues> ,
208 but retain these for backwards-comptibility with extant fines scripts.
210 Fines scripts should just supply the date range over which to calculate the fine.
212 C<&CalcFine> returns four values:
214 C<$amount> is the fine owed by the patron (see above).
216 C<$chargename> is the chargename field from the applicable record in
217 the categoryitem table, whatever that is.
219 C<$daycount> is the number of days between start and end dates, Calendar adjusted (where needed),
220 minus any applicable grace period.
222 C<$daycounttotal> is C<$daycount> without consideration of grace period.
224 FIXME - What is chargename supposed to be ?
226 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
227 or "Final Notice". But CalcFine never defined any value.
229 =cut
231 sub CalcFine {
232 my ( $item, $bortype, $branchcode, $difference ,$dues , $start_date, $end_date ) = @_;
233 $debug and warn sprintf("CalcFine(%s, %s, %s, %s, %s, %s, %s)",
234 ($item ? '{item}' : 'UNDEF'),
235 ($bortype || 'UNDEF'),
236 ($branchcode || 'UNDEF'),
237 ($difference || 'UNDEF'),
238 ($dues || 'UNDEF'),
239 ($start_date ? ($start_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF'),
240 ( $end_date ? ( $end_date->output('iso') || 'Not a C4::Dates object') : 'UNDEF')
242 my $dbh = C4::Context->dbh;
243 my $amount = 0;
244 my $daystocharge;
245 # get issuingrules (fines part will be used)
246 $debug and warn sprintf("CalcFine calling GetIssuingRule(%s, %s, %s)", $bortype, $item->{'itemtype'}, $branchcode);
247 my $data = C4::Circulation::GetIssuingRule($bortype, $item->{'itemtype'}, $branchcode);
248 if($difference) {
249 # if $difference is supplied, the difference has already been calculated, but we still need to adjust for the calendar.
250 # use copy-pasted functions from calendar module. (deprecated -- these functions will be removed from C4::Overdues ).
251 my $countspecialday = &GetSpecialHolidays($dues,$item->{itemnumber});
252 my $countrepeatableday = &GetRepeatableHolidays($dues,$item->{itemnumber},$difference);
253 my $countalldayclosed = $countspecialday + $countrepeatableday;
254 $daystocharge = $difference - $countalldayclosed;
255 } else {
256 # if $difference is not supplied, we have C4::Dates objects giving us the date range, and we use the calendar module.
257 if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
258 my $calendar = C4::Calendar->new( branchcode => $branchcode );
259 $daystocharge = $calendar->daysBetween( $start_date, $end_date );
260 } else {
261 $daystocharge = Date_to_Days(split('-',$end_date->output('iso'))) - Date_to_Days(split('-',$start_date->output('iso')));
264 # correct for grace period.
265 my $days_minus_grace = $daystocharge - $data->{'firstremind'};
266 if ($data->{'chargeperiod'} > 0 && $days_minus_grace > 0 ) {
267 $amount = int($daystocharge / $data->{'chargeperiod'}) * $data->{'fine'};
268 } else {
269 # a zero (or null) chargeperiod means no charge.
271 $amount = C4::Context->preference('maxFine') if(C4::Context->preference('maxFine') && ( $amount > C4::Context->preference('maxFine')));
272 $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
273 return ($amount, $data->{'chargename'}, $days_minus_grace, $daystocharge);
274 # FIXME: chargename is NEVER populated anywhere.
278 =head2 GetSpecialHolidays
280 &GetSpecialHolidays($date_dues,$itemnumber);
282 return number of special days between date of the day and date due
284 C<$date_dues> is the envisaged date of book return.
286 C<$itemnumber> is the book's item number.
288 =cut
290 sub GetSpecialHolidays {
291 my ( $date_dues, $itemnumber ) = @_;
293 # calcul the today date
294 my $today = join "-", &Today();
296 # return the holdingbranch
297 my $iteminfo = GetIssuesIteminfo($itemnumber);
299 # use sql request to find all date between date_due and today
300 my $dbh = C4::Context->dbh;
301 my $query =
302 qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
303 FROM `special_holidays`
304 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
305 AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
306 AND branchcode=?
308 my @result = GetWdayFromItemnumber($itemnumber);
309 my @result_date;
310 my $wday;
311 my $dateinsec;
312 my $sth = $dbh->prepare($query);
313 $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
314 ; # FIXME: just use NOW() in SQL instead of passing in $today
316 while ( my $special_date = $sth->fetchrow_hashref ) {
317 push( @result_date, $special_date );
320 my $specialdaycount = scalar(@result_date);
322 for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
323 $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
324 ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
325 localtime($dateinsec);
326 for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
327 if ( $wday == ( $result[$j]->{'weekday'} ) ) {
328 $specialdaycount--;
333 return $specialdaycount;
336 =head2 GetRepeatableHolidays
338 &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
340 return number of day closed between date of the day and date due
342 C<$date_dues> is the envisaged date of book return.
344 C<$itemnumber> is item number.
346 C<$difference> numbers of between day date of the day and date due
348 =cut
350 sub GetRepeatableHolidays {
351 my ( $date_dues, $itemnumber, $difference ) = @_;
352 my $dateinsec = UnixDate( $date_dues, "%o" );
353 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
354 localtime($dateinsec);
355 my @result = GetWdayFromItemnumber($itemnumber);
356 my @dayclosedcount;
357 my $j;
359 for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
360 my $k = $wday;
362 for ( $j = 0 ; $j < $difference ; $j++ ) {
363 if ( $result[$i]->{'weekday'} == $k ) {
364 push( @dayclosedcount, $k );
366 $k++;
367 ( $k = 0 ) if ( $k eq 7 );
370 return scalar(@dayclosedcount);
374 =head2 GetWayFromItemnumber
376 &Getwdayfromitemnumber($itemnumber);
378 return the different week day from repeatable_holidays table
380 C<$itemnumber> is item number.
382 =cut
384 sub GetWdayFromItemnumber {
385 my ($itemnumber) = @_;
386 my $iteminfo = GetIssuesIteminfo($itemnumber);
387 my @result;
388 my $query = qq|SELECT weekday
389 FROM repeatable_holidays
390 WHERE branchcode=?
392 my $sth = C4::Context->dbh->prepare($query);
394 $sth->execute( $iteminfo->{'branchcode'} );
395 while ( my $weekday = $sth->fetchrow_hashref ) {
396 push( @result, $weekday );
398 return @result;
402 =head2 GetIssuesIteminfo
404 &GetIssuesIteminfo($itemnumber);
406 return all data from issues about item
408 C<$itemnumber> is item number.
410 =cut
412 sub GetIssuesIteminfo {
413 my ($itemnumber) = @_;
414 my $dbh = C4::Context->dbh;
415 my $query = qq|SELECT *
416 FROM issues
417 WHERE itemnumber=?
419 my $sth = $dbh->prepare($query);
420 $sth->execute($itemnumber);
421 my ($issuesinfo) = $sth->fetchrow_hashref;
422 return $issuesinfo;
426 =head2 UpdateFine
428 &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
430 (Note: the following is mostly conjecture and guesswork.)
432 Updates the fine owed on an overdue book.
434 C<$itemnumber> is the book's item number.
436 C<$borrowernumber> is the borrower number of the patron who currently
437 has the book on loan.
439 C<$amount> is the current amount owed by the patron.
441 C<$type> will be used in the description of the fine.
443 C<$description> is a string that must be present in the description of
444 the fine. I think this is expected to be a date in DD/MM/YYYY format.
446 C<&UpdateFine> looks up the amount currently owed on the given item
447 and sets it to C<$amount>, creating, if necessary, a new entry in the
448 accountlines table of the Koha database.
450 =cut
453 # Question: Why should the caller have to
454 # specify both the item number and the borrower number? A book can't
455 # be on loan to two different people, so the item number should be
456 # sufficient.
458 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
460 sub UpdateFine {
461 my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
462 $debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
463 my $dbh = C4::Context->dbh;
464 # FIXME - What exactly is this query supposed to do? It looks up an
465 # entry in accountlines that matches the given item and borrower
466 # numbers, where the description contains $due, and where the
467 # account type has one of several values, but what does this _mean_?
468 # Does it look up existing fines for this item?
469 # FIXME - What are these various account types? ("FU", "O", "F", "M")
470 # "L" is LOST item
471 # "A" is Account Management Fee
472 # "N" is New Card
473 # "M" is Sundry
474 # "O" is Overdue ??
475 # "F" is Fine ??
476 # "FU" is Fine UPDATE??
477 # "Pay" is Payment
478 # "REF" is Cash Refund
479 my $sth = $dbh->prepare(
480 "SELECT * FROM accountlines
481 WHERE itemnumber=?
482 AND borrowernumber=?
483 AND accounttype IN ('FU','O','F','M')
484 AND description like ? "
486 $sth->execute( $itemnum, $borrowernumber, "%$due%" );
488 if ( my $data = $sth->fetchrow_hashref ) {
490 # we're updating an existing fine. Only modify if we're adding to the charge.
491 # Note that in the current implementation, you cannot pay against an accruing fine
492 # (i.e. , of accounttype 'FU'). Doing so will break accrual.
493 if ( $data->{'amount'} != $amount ) {
494 my $diff = $amount - $data->{'amount'};
495 $diff = 0 if ( $data->{amount} > $amount);
496 my $out = $data->{'amountoutstanding'} + $diff;
497 my $query = "
498 UPDATE accountlines
499 SET date=now(), amount=?, amountoutstanding=?,
500 lastincrement=?, accounttype='FU'
501 WHERE borrowernumber=?
502 AND itemnumber=?
503 AND accounttype IN ('FU','O')
504 AND description LIKE ?
505 LIMIT 1 ";
506 my $sth2 = $dbh->prepare($query);
507 # FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
508 # LIMIT 1 added to prevent multiple affected lines
509 # FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.
510 # But actually, we should just have a regular autoincrementing PK and forget accountline,
511 # including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
512 # FIXME: Why only 2 account types here?
513 $debug and print STDERR "UpdateFine query: $query\n" .
514 "w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
515 $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
516 } else {
517 # print "no update needed $data->{'amount'}"
519 } else {
520 my $sth4 = $dbh->prepare(
521 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
523 $sth4->execute($itemnum);
524 my $title = $sth4->fetchrow;
526 # # print "not in account";
527 # my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
528 # $sth3->execute;
530 # # FIXME - Make $accountno a scalar.
531 # my @accountno = $sth3->fetchrow_array;
532 # $sth3->finish;
533 # $accountno[0]++;
534 # begin transaction
535 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
536 my $desc = ($type ? "$type " : '') . "$title $due"; # FIXEDME, avoid whitespace prefix on empty $type
537 my $query = "INSERT INTO accountlines
538 (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
539 VALUES (?,?,now(),?,?,'FU',?,?,?)";
540 my $sth2 = $dbh->prepare($query);
541 $debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
542 $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
544 # logging action
545 &logaction(
546 "FINES",
547 $type,
548 $borrowernumber,
549 "due=".$due." amount=".$amount." itemnumber=".$itemnum
550 ) if C4::Context->preference("FinesLog");
553 =head2 BorType
555 $borrower = &BorType($borrowernumber);
557 Looks up a patron by borrower number.
559 C<$borrower> is a reference-to-hash whose keys are all of the fields
560 from the borrowers and categories tables of the Koha database. Thus,
561 C<$borrower> contains all information about both the borrower and
562 category he or she belongs to.
564 =cut
567 sub BorType {
568 my ($borrowernumber) = @_;
569 my $dbh = C4::Context->dbh;
570 my $sth = $dbh->prepare(
571 "SELECT * from borrowers
572 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
573 WHERE borrowernumber=?"
575 $sth->execute($borrowernumber);
576 return $sth->fetchrow_hashref;
579 =head2 ReplacementCost
581 $cost = &ReplacementCost($itemnumber);
583 Returns the replacement cost of the item with the given item number.
585 =cut
588 sub ReplacementCost {
589 my ($itemnum) = @_;
590 my $dbh = C4::Context->dbh;
591 my $sth =
592 $dbh->prepare("Select replacementprice from items where itemnumber=?");
593 $sth->execute($itemnum);
595 # FIXME - Use fetchrow_array or a slice.
596 my $data = $sth->fetchrow_hashref;
597 return ( $data->{'replacementprice'} );
600 =head2 GetFine
602 $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
604 return the total of fine
606 C<$itemnum> is item number
608 C<$borrowernumber> is the borrowernumber
610 =cut
613 sub GetFine {
614 my ( $itemnum, $borrowernumber ) = @_;
615 my $dbh = C4::Context->dbh();
616 my $query = "SELECT sum(amountoutstanding) FROM accountlines
617 where accounttype like 'F%'
618 AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?";
619 my $sth = $dbh->prepare($query);
620 $sth->execute( $itemnum, $borrowernumber );
621 my $data = $sth->fetchrow_hashref();
622 return ( $data->{'sum(amountoutstanding)'} );
626 =head2 GetIssuingRules
628 FIXME - This sub should be deprecated and removed.
629 It ignores branch and defaults.
631 $data = &GetIssuingRules($itemtype,$categorycode);
633 Looks up for all issuingrules an item info
635 C<$itemnumber> is a reference-to-hash whose keys are all of the fields
636 from the borrowers and categories tables of the Koha database. Thus,
638 C<$categorycode> contains information about borrowers category
640 C<$data> contains all information about both the borrower and
641 category he or she belongs to.
642 =cut
644 sub GetIssuingRules {
645 warn "GetIssuingRules is deprecated: use GetIssuingRule from C4::Circulation instead.";
646 my ($itemtype,$categorycode)=@_;
647 my $dbh = C4::Context->dbh();
648 my $query=qq|SELECT *
649 FROM issuingrules
650 WHERE issuingrules.itemtype=?
651 AND issuingrules.categorycode=?
653 my $sth = $dbh->prepare($query);
654 # print $query;
655 $sth->execute($itemtype,$categorycode);
656 return $sth->fetchrow_hashref;
660 sub ReplacementCost2 {
661 my ( $itemnum, $borrowernumber ) = @_;
662 my $dbh = C4::Context->dbh();
663 my $query = "SELECT amountoutstanding
664 FROM accountlines
665 WHERE accounttype like 'L'
666 AND amountoutstanding > 0
667 AND itemnumber = ?
668 AND borrowernumber= ?";
669 my $sth = $dbh->prepare($query);
670 $sth->execute( $itemnum, $borrowernumber );
671 my $data = $sth->fetchrow_hashref();
672 return ( $data->{'amountoutstanding'} );
676 =head2 GetNextIdNotify
678 ($result) = &GetNextIdNotify($reference);
680 Returns the new file number
682 C<$result> contains the next file number
684 C<$reference> contains the beggining of file number
686 =cut
688 sub GetNextIdNotify {
689 my ($reference) = @_;
690 my $query = qq|SELECT max(notify_id)
691 FROM accountlines
692 WHERE notify_id like \"$reference%\"
695 # AND borrowernumber=?|;
696 my $dbh = C4::Context->dbh;
697 my $sth = $dbh->prepare($query);
698 $sth->execute();
699 my $result = $sth->fetchrow;
700 my $count;
701 if ( $result eq '' ) {
702 ( $result = $reference . "01" );
704 else {
705 $count = substr( $result, 6 ) + 1;
707 if ( $count < 10 ) {
708 ( $count = "0" . $count );
710 $result = $reference . $count;
712 return $result;
715 =head2 NumberNotifyId
717 (@notify) = &NumberNotifyId($borrowernumber);
719 Returns amount for all file per borrowers
720 C<@notify> array contains all file per borrowers
722 C<$notify_id> contains the file number for the borrower number nad item number
724 =cut
726 sub NumberNotifyId{
727 my ($borrowernumber)=@_;
728 my $dbh = C4::Context->dbh;
729 my $query=qq| SELECT distinct(notify_id)
730 FROM accountlines
731 WHERE borrowernumber=?|;
732 my @notify;
733 my $sth = $dbh->prepare($query);
734 $sth->execute($borrowernumber);
735 while ( my ($numberofnotify) = $sth->fetchrow ) {
736 push( @notify, $numberofnotify );
738 return (@notify);
741 =head2 AmountNotify
743 ($totalnotify) = &AmountNotify($notifyid);
745 Returns amount for all file per borrowers
746 C<$notifyid> is the file number
748 C<$totalnotify> contains amount of a file
750 C<$notify_id> contains the file number for the borrower number and item number
752 =cut
754 sub AmountNotify{
755 my ($notifyid,$borrowernumber)=@_;
756 my $dbh = C4::Context->dbh;
757 my $query=qq| SELECT sum(amountoutstanding)
758 FROM accountlines
759 WHERE notify_id=? AND borrowernumber = ?|;
760 my $sth=$dbh->prepare($query);
761 $sth->execute($notifyid,$borrowernumber);
762 my $totalnotify=$sth->fetchrow;
763 $sth->finish;
764 return ($totalnotify);
768 =head2 GetNotifyId
770 ($notify_id) = &GetNotifyId($borrowernumber,$itemnumber);
772 Returns the file number per borrower and itemnumber
774 C<$borrowernumber> is a reference-to-hash whose keys are all of the fields
775 from the items tables of the Koha database. Thus,
777 C<$itemnumber> contains the borrower categorycode
779 C<$notify_id> contains the file number for the borrower number nad item number
781 =cut
783 sub GetNotifyId {
784 my ( $borrowernumber, $itemnumber ) = @_;
785 my $query = qq|SELECT notify_id
786 FROM accountlines
787 WHERE borrowernumber=?
788 AND itemnumber=?
789 AND (accounttype='FU' or accounttype='O')|;
790 my $dbh = C4::Context->dbh;
791 my $sth = $dbh->prepare($query);
792 $sth->execute( $borrowernumber, $itemnumber );
793 my ($notify_id) = $sth->fetchrow;
794 $sth->finish;
795 return ($notify_id);
798 =head2 CreateItemAccountLine
800 () = &CreateItemAccountLine($borrowernumber,$itemnumber,$date,$amount,$description,$accounttype,$amountoutstanding,$timestamp,$notify_id,$level);
802 update the account lines with file number or with file level
804 C<$items> is a reference-to-hash whose keys are all of the fields
805 from the items tables of the Koha database. Thus,
807 C<$itemnumber> contains the item number
809 C<$borrowernumber> contains the borrower number
811 C<$date> contains the date of the day
813 C<$amount> contains item price
815 C<$description> contains the descritpion of accounttype
817 C<$accounttype> contains the account type
819 C<$amountoutstanding> contains the $amountoutstanding
821 C<$timestamp> contains the timestamp with time and the date of the day
823 C<$notify_id> contains the file number
825 C<$level> contains the file level
827 =cut
829 sub CreateItemAccountLine {
830 my (
831 $borrowernumber, $itemnumber, $date, $amount,
832 $description, $accounttype, $amountoutstanding, $timestamp,
833 $notify_id, $level
834 ) = @_;
835 my $dbh = C4::Context->dbh;
836 my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
837 my $query = "INSERT into accountlines
838 (borrowernumber,accountno,itemnumber,date,amount,description,accounttype,amountoutstanding,timestamp,notify_id,notify_level)
839 VALUES
840 (?,?,?,?,?,?,?,?,?,?,?)";
842 my $sth = $dbh->prepare($query);
843 $sth->execute(
844 $borrowernumber, $nextaccntno, $itemnumber,
845 $date, $amount, $description,
846 $accounttype, $amountoutstanding, $timestamp,
847 $notify_id, $level
851 =head2 UpdateAccountLines
853 () = &UpdateAccountLines($notify_id,$notify_level,$borrowernumber,$itemnumber);
855 update the account lines with file number or with file level
857 C<$items> is a reference-to-hash whose keys are all of the fields
858 from the items tables of the Koha database. Thus,
860 C<$itemnumber> contains the item number
862 C<$notify_id> contains the file number
864 C<$notify_level> contains the file level
866 C<$borrowernumber> contains the borrowernumber
868 =cut
870 sub UpdateAccountLines {
871 my ( $notify_id, $notify_level, $borrowernumber, $itemnumber ) = @_;
872 my $query;
873 if ( $notify_id eq '' ) {
874 $query = qq|UPDATE accountlines
875 SET notify_level=?
876 WHERE borrowernumber=? AND itemnumber=?
877 AND (accounttype='FU' or accounttype='O')|;
878 } else {
879 $query = qq|UPDATE accountlines
880 SET notify_id=?, notify_level=?
881 WHERE borrowernumber=?
882 AND itemnumber=?
883 AND (accounttype='FU' or accounttype='O')|;
886 my $sth = C4::Context->dbh->prepare($query);
887 if ( $notify_id eq '' ) {
888 $sth->execute( $notify_level, $borrowernumber, $itemnumber );
889 } else {
890 $sth->execute( $notify_id, $notify_level, $borrowernumber, $itemnumber );
894 =head2 GetItems
896 ($items) = &GetItems($itemnumber);
898 Returns the list of all delays from overduerules.
900 C<$items> is a reference-to-hash whose keys are all of the fields
901 from the items tables of the Koha database. Thus,
903 C<$itemnumber> contains the borrower categorycode
905 =cut
907 # FIXME: This is a bad function to have here.
908 # Shouldn't it be in C4::Items?
909 # Shouldn't it be called GetItem since you only get 1 row?
910 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
912 sub GetItems {
913 my $itemnumber = shift or return;
914 my $query = qq|SELECT *
915 FROM items
916 WHERE itemnumber=?|;
917 my $sth = C4::Context->dbh->prepare($query);
918 $sth->execute($itemnumber);
919 my ($items) = $sth->fetchrow_hashref;
920 return ($items);
923 =head2 GetOverdueDelays
925 (@delays) = &GetOverdueDelays($categorycode);
927 Returns the list of all delays from overduerules.
929 C<@delays> it's an array contains the three delays from overduerules table
931 C<$categorycode> contains the borrower categorycode
933 =cut
935 sub GetOverdueDelays {
936 my ($category) = @_;
937 my $query = qq|SELECT delay1,delay2,delay3
938 FROM overduerules
939 WHERE categorycode=?|;
940 my $sth = C4::Context->dbh->prepare($query);
941 $sth->execute($category);
942 my (@delays) = $sth->fetchrow_array;
943 return (@delays);
946 =head2 GetBranchcodesWithOverdueRules
948 =over 4
950 my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
952 returns a list of branch codes for branches with overdue rules defined.
954 =back
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.biblionumber,
1181 issues.date_due,
1182 issues.returndate,
1183 issues.branchcode,
1184 branches.branchname,
1185 items.barcode,
1186 items.itemcallnumber,
1187 items.location,
1188 items.itemnumber,
1189 itemtypes.description,
1190 accountlines.notify_id,
1191 accountlines.notify_level,
1192 accountlines.amountoutstanding
1193 FROM accountlines
1194 LEFT JOIN issues ON issues.itemnumber = accountlines.itemnumber
1195 AND issues.borrowernumber = accountlines.borrowernumber
1196 LEFT JOIN borrowers ON borrowers.borrowernumber = accountlines.borrowernumber
1197 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1198 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1199 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1200 LEFT JOIN itemtypes ON itemtypes.itemtype = $itype_link
1201 LEFT JOIN branches ON branches.branchcode = issues.branchcode
1202 WHERE (accountlines.amountoutstanding != '0.000000')
1203 AND (accountlines.accounttype = 'FU' )
1204 AND (issues.branchcode = ? )
1205 AND (issues.date_due < CURDATE())
1207 my @getoverdues;
1208 my $i = 0;
1209 my $sth;
1210 if ($location) {
1211 $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
1212 $sth->execute($branch, $location);
1213 } else {
1214 $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
1215 $sth->execute($branch);
1217 while ( my $data = $sth->fetchrow_hashref ) {
1218 #check if the document has already been notified
1219 my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
1220 if ($countnotify eq '0') {
1221 $getoverdues[$i] = $data;
1222 $i++;
1225 return (@getoverdues);
1229 =head2 AddNotifyLine
1231 &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
1233 Creat a line into notify, if the method is phone, the notification_send_date is implemented to
1235 =cut
1237 sub AddNotifyLine {
1238 my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
1239 my $dbh = C4::Context->dbh;
1240 if ( $method eq "phone" ) {
1241 my $sth = $dbh->prepare(
1242 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
1243 VALUES (?,?,now(),now(),?,?,?)"
1245 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1246 $notifyId );
1248 else {
1249 my $sth = $dbh->prepare(
1250 "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
1251 VALUES (?,?,now(),?,?,?)"
1253 $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
1254 $notifyId );
1256 return 1;
1259 =head2 RemoveNotifyLine
1261 &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
1263 Cancel a notification
1265 =cut
1267 sub RemoveNotifyLine {
1268 my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
1269 my $dbh = C4::Context->dbh;
1270 my $sth = $dbh->prepare(
1271 "DELETE FROM notifys
1272 WHERE
1273 borrowernumber=?
1274 AND itemnumber=?
1275 AND notify_date=?"
1277 $sth->execute( $borrowernumber, $itemnumber, $notify_date );
1278 return 1;
1282 __END__
1284 =head1 AUTHOR
1286 Koha Developement team <info@koha.org>
1288 =cut