3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #use warnings; FIXME - Bug 2505
26 use C4::Dates qw(format_date_in_iso format_date);
27 use String::Random qw( random_string );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
37 use C4::NewsChannels; #get slip news
39 use DateTime::Format::DateParse;
41 use Koha::Borrower::Debarments qw(IsDebarred);
42 use Text::Unaccent qw( unac_string );
43 use Koha::AuthUtils qw(hash_password);
45 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
48 $VERSION = 3.07.00.049;
49 $debug = $ENV{DEBUG} || 0;
61 &GetMemberIssuesAndFines
68 &GetFirstValidEmailAddress
69 &GetNoticeEmailAddress
80 &GetHideLostItemsPreference
83 &GetMemberAccountRecords
84 &GetBorNotifyAcctRecord
88 GetBorrowerCategorycode
89 &GetBorrowercategoryList
91 &GetBorrowersToExpunge
92 &GetBorrowersWhoHaveNeverBorrowed
93 &GetBorrowersWithIssuesHistoryOlderThan
103 GetBorrowersWithEmail
125 &ExtendMemberSubscriptionTo
143 C4::Members - Perl Module containing convenience functions for member handling
151 This module contains routines for adding, modifying and deleting members/patrons/borrowers
157 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
158 $columns_out, $search_on_fields,$searchtype);
160 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
162 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
163 refer to C4::SQLHelper:SearchInTable().
165 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
166 and cardnumber unless C<&search_on_fields> is defined
170 $borrowers = Search('abcd', 'cardnumber');
172 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
176 sub _express_member_find {
179 # this is used by circulation everytime a new borrowers cardnumber is scanned
180 # so we can check an exact match first, if that works return, otherwise do the rest
181 my $dbh = C4::Context->dbh;
182 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
183 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
184 return( {"borrowernumber"=>$borrowernumber} );
187 my ($search_on_fields, $searchtype);
188 if ( length($filter) == 1 ) {
189 $search_on_fields = [ qw(surname) ];
190 $searchtype = 'start_with';
192 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
193 $searchtype = 'contain';
196 return (undef, $search_on_fields, $searchtype);
200 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
205 if ( my $fr = ref $filter ) {
206 if ( $fr eq "HASH" ) {
207 if ( my $search_string = $filter->{''} ) {
208 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
209 if ($member_filter) {
210 $filter = $member_filter;
213 $search_on_fields ||= $member_search_on_fields;
214 $searchtype ||= $member_searchtype;
219 $search_string = $filter;
223 $search_string = $filter;
224 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
225 if ($member_filter) {
226 $filter = $member_filter;
229 $search_on_fields ||= $member_search_on_fields;
230 $searchtype ||= $member_searchtype;
234 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
235 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
236 if(scalar(@$matching_records)>0) {
237 if ( my $fr = ref $filter ) {
238 if ( $fr eq "HASH" ) {
240 $filter = [ $filter ];
242 push @$filter, { %f, "borrowernumber"=>$$matching_records };
245 push @$filter, {"borrowernumber"=>$matching_records};
249 $filter = [ $filter ];
250 push @$filter, {"borrowernumber"=>$matching_records};
255 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
256 # Mentioning for the reference
258 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
259 if ( my $userenv = C4::Context->userenv ) {
260 my $branch = $userenv->{'branch'};
261 if ( !C4::Context->IsSuperLibrarian() && $branch ){
262 if (my $fr = ref $filter) {
263 if ( $fr eq "HASH" ) {
264 $filter->{branchcode} = $branch;
268 $_ = { '' => $_ } unless ref $_;
269 $_->{branchcode} = $branch;
274 $filter = { '' => $filter, branchcode => $branch };
280 if ($found_borrower) {
281 $searchtype = "exact";
283 $searchtype ||= "start_with";
285 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
288 =head2 GetMemberDetails
290 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
292 Looks up a patron and returns information about him or her. If
293 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
294 up the borrower by number; otherwise, it looks up the borrower by card
297 C<$borrower> is a reference-to-hash whose keys are the fields of the
298 borrowers table in the Koha database. In addition,
299 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
300 about the patron. Its keys act as flags :
302 if $borrower->{flags}->{LOST} {
303 # Patron's card was reported lost
306 If the state of a flag means that the patron should not be
307 allowed to borrow any more books, then it will have a C<noissues> key
310 See patronflags for more details.
312 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
313 about the top-level permissions flags set for the borrower. For example,
314 if a user has the "editcatalogue" permission,
315 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
320 sub GetMemberDetails {
321 my ( $borrowernumber, $cardnumber ) = @_;
322 my $dbh = C4::Context->dbh;
325 if ($borrowernumber) {
326 $sth = $dbh->prepare("
329 categories.description,
330 categories.BlockExpiredPatronOpacActions,
334 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
335 WHERE borrowernumber = ?
337 $sth->execute($borrowernumber);
339 elsif ($cardnumber) {
340 $sth = $dbh->prepare("
343 categories.description,
344 categories.BlockExpiredPatronOpacActions,
348 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
351 $sth->execute($cardnumber);
356 my $borrower = $sth->fetchrow_hashref;
357 return unless $borrower;
358 my ($amount) = GetMemberAccountRecords( $borrowernumber);
359 $borrower->{'amountoutstanding'} = $amount;
360 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
361 my $flags = patronflags( $borrower);
364 $sth = $dbh->prepare("select bit,flag from userflags");
366 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
367 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
368 $accessflagshash->{$flag} = 1;
371 $borrower->{'flags'} = $flags;
372 $borrower->{'authflags'} = $accessflagshash;
374 # For the purposes of making templates easier, we'll define a
375 # 'showname' which is the alternate form the user's first name if
376 # 'other name' is defined.
377 if ($borrower->{category_type} eq 'I') {
378 $borrower->{'showname'} = $borrower->{'othernames'};
379 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
381 $borrower->{'showname'} = $borrower->{'firstname'};
384 # Handle setting the true behavior for BlockExpiredPatronOpacActions
385 $borrower->{'BlockExpiredPatronOpacActions'} =
386 C4::Context->preference('BlockExpiredPatronOpacActions')
387 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
389 $borrower->{'is_expired'} = 0;
390 $borrower->{'is_expired'} = 1 if
391 defined($borrower->{dateexpiry}) &&
392 $borrower->{'dateexpiry'} ne '0000-00-00' &&
393 Date_to_Days( Today() ) >
394 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
396 return ($borrower); #, $flags, $accessflagshash);
401 $flags = &patronflags($patron);
403 This function is not exported.
405 The following will be set where applicable:
406 $flags->{CHARGES}->{amount} Amount of debt
407 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
408 $flags->{CHARGES}->{message} Message -- deprecated
410 $flags->{CREDITS}->{amount} Amount of credit
411 $flags->{CREDITS}->{message} Message -- deprecated
413 $flags->{ GNA } Patron has no valid address
414 $flags->{ GNA }->{noissues} Set for each GNA
415 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
417 $flags->{ LOST } Patron's card reported lost
418 $flags->{ LOST }->{noissues} Set for each LOST
419 $flags->{ LOST }->{message} Message -- deprecated
421 $flags->{DBARRED} Set if patron debarred, no access
422 $flags->{DBARRED}->{noissues} Set for each DBARRED
423 $flags->{DBARRED}->{message} Message -- deprecated
426 $flags->{ NOTES }->{message} The note itself. NOT deprecated
428 $flags->{ ODUES } Set if patron has overdue books.
429 $flags->{ ODUES }->{message} "Yes" -- deprecated
430 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
431 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
433 $flags->{WAITING} Set if any of patron's reserves are available
434 $flags->{WAITING}->{message} Message -- deprecated
435 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
439 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
440 overdue items. Its elements are references-to-hash, each describing an
441 overdue item. The keys are selected fields from the issues, biblio,
442 biblioitems, and items tables of the Koha database.
444 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
445 the overdue items, one per line. Deprecated.
447 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
448 available items. Each element is a reference-to-hash whose keys are
449 fields from the reserves table of the Koha database.
453 All the "message" fields that include language generated in this function are deprecated,
454 because such strings belong properly in the display layer.
456 The "message" field that comes from the DB is OK.
460 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
461 # FIXME rename this function.
464 my ( $patroninformation) = @_;
465 my $dbh=C4::Context->dbh;
466 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
469 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
470 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
471 $flaginfo{'amount'} = sprintf "%.02f", $owing;
472 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
473 $flaginfo{'noissues'} = 1;
475 $flags{'CHARGES'} = \%flaginfo;
477 elsif ( $balance < 0 ) {
479 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
480 $flaginfo{'amount'} = sprintf "%.02f", $balance;
481 $flags{'CREDITS'} = \%flaginfo;
483 if ( $patroninformation->{'gonenoaddress'}
484 && $patroninformation->{'gonenoaddress'} == 1 )
487 $flaginfo{'message'} = 'Borrower has no valid address.';
488 $flaginfo{'noissues'} = 1;
489 $flags{'GNA'} = \%flaginfo;
491 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
493 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
494 $flaginfo{'noissues'} = 1;
495 $flags{'LOST'} = \%flaginfo;
497 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
498 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
500 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
501 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
502 $flaginfo{'noissues'} = 1;
503 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
504 $flags{'DBARRED'} = \%flaginfo;
507 if ( $patroninformation->{'borrowernotes'}
508 && $patroninformation->{'borrowernotes'} )
511 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
512 $flags{'NOTES'} = \%flaginfo;
514 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
515 if ( $odues && $odues > 0 ) {
517 $flaginfo{'message'} = "Yes";
518 $flaginfo{'itemlist'} = $itemsoverdue;
519 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
522 $flaginfo{'itemlisttext'} .=
523 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
525 $flags{'ODUES'} = \%flaginfo;
527 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
528 my $nowaiting = scalar @itemswaiting;
529 if ( $nowaiting > 0 ) {
531 $flaginfo{'message'} = "Reserved items available";
532 $flaginfo{'itemlist'} = \@itemswaiting;
533 $flags{'WAITING'} = \%flaginfo;
541 $borrower = &GetMember(%information);
543 Retrieve the first patron record meeting on criteria listed in the
544 C<%information> hash, which should contain one or more
545 pairs of borrowers column names and values, e.g.,
547 $borrower = GetMember(borrowernumber => id);
549 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
550 the C<borrowers> table in the Koha database.
552 FIXME: GetMember() is used throughout the code as a lookup
553 on a unique key such as the borrowernumber, but this meaning is not
554 enforced in the routine itself.
560 my ( %information ) = @_;
561 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
562 #passing mysql's kohaadmin?? Makes no sense as a query
565 my $dbh = C4::Context->dbh;
567 q{SELECT borrowers.*, categories.category_type, categories.description
569 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
572 for (keys %information ) {
580 if (defined $information{$_}) {
582 push @values, $information{$_};
585 $select .= "$_ IS NULL";
588 $debug && warn $select, " ",values %information;
589 my $sth = $dbh->prepare("$select");
590 $sth->execute(map{$information{$_}} keys %information);
591 my $data = $sth->fetchall_arrayref({});
592 #FIXME interface to this routine now allows generation of a result set
593 #so whole array should be returned but bowhere in the current code expects this
601 =head2 GetMemberRelatives
603 @borrowernumbers = GetMemberRelatives($borrowernumber);
605 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
608 sub GetMemberRelatives {
609 my $borrowernumber = shift;
610 my $dbh = C4::Context->dbh;
614 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
615 my $sth = $dbh->prepare($query);
616 $sth->execute($borrowernumber);
617 my $data = $sth->fetchrow_arrayref();
618 push @glist, $data->[0] if $data->[0];
619 my $guarantor = $data->[0] ? $data->[0] : undef;
622 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
623 $sth = $dbh->prepare($query);
624 $sth->execute($borrowernumber);
625 while ($data = $sth->fetchrow_arrayref()) {
626 push @glist, $data->[0];
629 # Getting sibling guarantees
631 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
632 $sth = $dbh->prepare($query);
633 $sth->execute($guarantor);
634 while ($data = $sth->fetchrow_arrayref()) {
635 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
642 =head2 IsMemberBlocked
644 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
646 Returns whether a patron has overdue items that may result
647 in a block or whether the patron has active fine days
648 that would block circulation privileges.
650 C<$block_status> can have the following values:
652 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
654 -1 if the patron has overdue items, in which case C<$count> is the number of them
656 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
658 Outstanding fine days are checked before current overdue items
661 FIXME: this needs to be split into two functions; a potential block
662 based on the number of current overdue items could be orthogonal
663 to a block based on whether the patron has any fine days accrued.
667 sub IsMemberBlocked {
668 my $borrowernumber = shift;
669 my $dbh = C4::Context->dbh;
671 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
673 return ( 1, $blockeddate ) if $blockeddate;
675 # if he have late issues
676 my $sth = $dbh->prepare(
677 "SELECT COUNT(*) as latedocs
679 WHERE borrowernumber = ?
680 AND date_due < now()"
682 $sth->execute($borrowernumber);
683 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
685 return ( -1, $latedocs ) if $latedocs > 0;
690 =head2 GetMemberIssuesAndFines
692 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
694 Returns aggregate data about items borrowed by the patron with the
695 given borrowernumber.
697 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
698 number of overdue items the patron currently has borrowed. C<$issue_count> is the
699 number of books the patron currently has borrowed. C<$total_fines> is
700 the total fine currently due by the borrower.
705 sub GetMemberIssuesAndFines {
706 my ( $borrowernumber ) = @_;
707 my $dbh = C4::Context->dbh;
708 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
710 $debug and warn $query."\n";
711 my $sth = $dbh->prepare($query);
712 $sth->execute($borrowernumber);
713 my $issue_count = $sth->fetchrow_arrayref->[0];
715 $sth = $dbh->prepare(
716 "SELECT COUNT(*) FROM issues
717 WHERE borrowernumber = ?
718 AND date_due < now()"
720 $sth->execute($borrowernumber);
721 my $overdue_count = $sth->fetchrow_arrayref->[0];
723 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
724 $sth->execute($borrowernumber);
725 my $total_fines = $sth->fetchrow_arrayref->[0];
727 return ($overdue_count, $issue_count, $total_fines);
733 my @columns = C4::Member::columns();
735 Returns an array of borrowers' table columns on success,
736 and an empty array on failure.
742 # Pure ANSI SQL goodness.
743 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
745 # Get the database handle.
746 my $dbh = C4::Context->dbh;
748 # Run the SQL statement to load STH's readonly properties.
749 my $sth = $dbh->prepare($sql);
750 my $rv = $sth->execute();
752 # This only fails if the table doesn't exist.
753 # This will always be called AFTER an install or upgrade,
754 # so borrowers will exist!
756 if ($sth->{NUM_OF_FIELDS}>0) {
757 @data = @{$sth->{NAME}};
768 my $success = ModMember(borrowernumber => $borrowernumber,
769 [ field => value ]... );
771 Modify borrower's data. All date fields should ALREADY be in ISO format.
774 true on success, or false on failure
780 # test to know if you must update or not the borrower password
781 if (exists $data{password}) {
782 if ($data{password} eq '****' or $data{password} eq '') {
783 delete $data{password};
785 $data{password} = hash_password($data{password});
788 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
789 my $execute_success=UpdateInTable("borrowers",\%data);
790 if ($execute_success) { # only proceed if the update was a success
791 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
792 # so when we update information for an adult we should check for guarantees and update the relevant part
793 # of their records, ie addresses and phone numbers
794 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
795 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
796 # is adult check guarantees;
797 UpdateGuarantees(%data);
800 # If the patron changes to a category with enrollment fee, we add a fee
801 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
802 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
805 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
807 return $execute_success;
812 $borrowernumber = &AddMember(%borrower);
814 insert new borrower into table
815 Returns the borrowernumber upon success
817 Returns as undef upon any db error without further processing
824 my $dbh = C4::Context->dbh;
826 # generate a proper login if none provided
827 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
829 # add expiration date if it isn't already there
830 unless ( $data{'dateexpiry'} ) {
831 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
834 # add enrollment date if it isn't already there
835 unless ( $data{'dateenrolled'} ) {
836 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
839 # create a disabled account if no password provided
840 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
841 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
843 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
844 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
846 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
848 return $data{'borrowernumber'};
853 my $uniqueness = Check_Userid($userid,$borrowernumber);
855 $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
857 If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
860 0 for not unique (i.e. this $userid already exists)
861 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
866 my ($uid,$member) = @_;
867 my $dbh = C4::Context->dbh;
870 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
871 $sth->execute( $uid, $member );
872 if ( (( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref )) or
873 (( $uid ne '' ) && ( $uid eq C4::Context->config('user') )) ) {
881 =head2 Generate_Userid
883 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
885 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
887 $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
890 new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
894 sub Generate_Userid {
895 my ($borrowernumber, $firstname, $surname) = @_;
898 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
900 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
901 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
902 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
903 $newuid = unac_string('utf-8',$newuid);
904 $newuid .= $offset unless $offset == 0;
907 } while (!Check_Userid($newuid,$borrowernumber));
913 my ( $uid, $member, $digest ) = @_;
914 my $dbh = C4::Context->dbh;
916 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
917 #Then we need to tell the user and have them create a new one.
921 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
922 $sth->execute( $uid, $member );
923 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
927 #Everything is good so we can update the information.
930 "update borrowers set userid=?, password=? where borrowernumber=?");
931 $sth->execute( $uid, $digest, $member );
935 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
941 =head2 fixup_cardnumber
943 Warning: The caller is responsible for locking the members table in write
944 mode, to avoid database corruption.
948 use vars qw( @weightings );
949 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
951 sub fixup_cardnumber {
952 my ($cardnumber) = @_;
953 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
955 # Find out whether member numbers should be generated
956 # automatically. Should be either "1" or something else.
957 # Defaults to "0", which is interpreted as "no".
959 # if ($cardnumber !~ /\S/ && $autonumber_members) {
960 ($autonumber_members) or return $cardnumber;
961 my $checkdigit = C4::Context->preference('checkdigit');
962 my $dbh = C4::Context->dbh;
963 if ( $checkdigit and $checkdigit eq 'katipo' ) {
965 # if checkdigit is selected, calculate katipo-style cardnumber.
966 # otherwise, just use the max()
967 # purpose: generate checksum'd member numbers.
968 # We'll assume we just got the max value of digits 2-8 of member #'s
969 # from the database and our job is to increment that by one,
970 # determine the 1st and 9th digits and return the full string.
971 my $sth = $dbh->prepare(
972 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
975 my $data = $sth->fetchrow_hashref;
976 $cardnumber = $data->{new_num};
977 if ( !$cardnumber ) { # If DB has no values,
978 $cardnumber = 1000000; # start at 1000000
984 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
985 # read weightings, left to right, 1 char at a time
986 my $temp1 = $weightings[$i];
988 # sequence left to right, 1 char at a time
989 my $temp2 = substr( $cardnumber, $i, 1 );
991 # mult each char 1-7 by its corresponding weighting
992 $sum += $temp1 * $temp2;
995 my $rem = ( $sum % 11 );
996 $rem = 'X' if $rem == 10;
998 return "V$cardnumber$rem";
1001 my $sth = $dbh->prepare(
1002 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
1005 my ($result) = $sth->fetchrow;
1008 return $cardnumber; # just here as a fallback/reminder
1011 =head2 GetGuarantees
1013 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1014 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1015 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1017 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1018 with children) and looks up the borrowers who are guaranteed by that
1019 borrower (i.e., the patron's children).
1021 C<&GetGuarantees> returns two values: an integer giving the number of
1022 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1023 of references to hash, which gives the actual results.
1029 my ($borrowernumber) = @_;
1030 my $dbh = C4::Context->dbh;
1033 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1035 $sth->execute($borrowernumber);
1038 my $data = $sth->fetchall_arrayref({});
1039 return ( scalar(@$data), $data );
1042 =head2 UpdateGuarantees
1044 &UpdateGuarantees($parent_borrno);
1047 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1048 with the modified information
1053 sub UpdateGuarantees {
1055 my $dbh = C4::Context->dbh;
1056 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1057 foreach my $guarantee (@$guarantees){
1058 my $guaquery = qq|UPDATE borrowers
1059 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1060 WHERE borrowernumber=?
1062 my $sth = $dbh->prepare($guaquery);
1063 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1066 =head2 GetPendingIssues
1068 my $issues = &GetPendingIssues(@borrowernumber);
1070 Looks up what the patron with the given borrowernumber has borrowed.
1072 C<&GetPendingIssues> returns a
1073 reference-to-array where each element is a reference-to-hash; the
1074 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1075 The keys include C<biblioitems> fields except marc and marcxml.
1080 sub GetPendingIssues {
1081 my @borrowernumbers = @_;
1083 unless (@borrowernumbers ) { # return a ref_to_array
1084 return \@borrowernumbers; # to not cause surprise to caller
1087 # Borrowers part of the query
1089 for (my $i = 0; $i < @borrowernumbers; $i++) {
1090 $bquery .= ' issues.borrowernumber = ?';
1091 if ($i < $#borrowernumbers ) {
1096 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1097 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1098 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1099 # FIXME: namespace collision: other collisions possible.
1100 # FIXME: most of this data isn't really being used by callers.
1107 biblioitems.itemtype,
1110 biblioitems.publicationyear,
1111 biblioitems.publishercode,
1112 biblioitems.volumedate,
1113 biblioitems.volumedesc,
1116 borrowers.firstname,
1118 borrowers.cardnumber,
1119 issues.timestamp AS timestamp,
1120 issues.renewals AS renewals,
1121 issues.borrowernumber AS borrowernumber,
1122 items.renewals AS totalrenewals
1124 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1125 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1126 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1127 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1130 ORDER BY issues.issuedate"
1133 my $sth = C4::Context->dbh->prepare($query);
1134 $sth->execute(@borrowernumbers);
1135 my $data = $sth->fetchall_arrayref({});
1136 my $tz = C4::Context->tz();
1137 my $today = DateTime->now( time_zone => $tz);
1138 foreach (@{$data}) {
1139 if ($_->{issuedate}) {
1140 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1142 $_->{date_due} or next;
1143 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1144 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1153 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1155 Looks up what the patron with the given borrowernumber has borrowed,
1156 and sorts the results.
1158 C<$sortkey> is the name of a field on which to sort the results. This
1159 should be the name of a field in the C<issues>, C<biblio>,
1160 C<biblioitems>, or C<items> table in the Koha database.
1162 C<$limit> is the maximum number of results to return.
1164 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1165 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1166 C<items> tables of the Koha database.
1172 my ( $borrowernumber, $order, $limit ) = @_;
1174 my $dbh = C4::Context->dbh;
1176 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1178 LEFT JOIN items on items.itemnumber=issues.itemnumber
1179 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1180 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1181 WHERE borrowernumber=?
1183 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1185 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1186 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1187 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1188 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1189 order by ' . $order;
1191 $query .= " limit $limit";
1194 my $sth = $dbh->prepare($query);
1195 $sth->execute( $borrowernumber, $borrowernumber );
1196 return $sth->fetchall_arrayref( {} );
1200 =head2 GetMemberAccountRecords
1202 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1204 Looks up accounting data for the patron with the given borrowernumber.
1206 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1207 reference-to-array, where each element is a reference-to-hash; the
1208 keys are the fields of the C<accountlines> table in the Koha database.
1209 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1210 total amount outstanding for all of the account lines.
1214 sub GetMemberAccountRecords {
1215 my ($borrowernumber) = @_;
1216 my $dbh = C4::Context->dbh;
1222 WHERE borrowernumber=?);
1223 $strsth.=" ORDER BY date desc,timestamp DESC";
1224 my $sth= $dbh->prepare( $strsth );
1225 $sth->execute( $borrowernumber );
1228 while ( my $data = $sth->fetchrow_hashref ) {
1229 if ( $data->{itemnumber} ) {
1230 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1231 $data->{biblionumber} = $biblio->{biblionumber};
1232 $data->{title} = $biblio->{title};
1234 $acctlines[$numlines] = $data;
1236 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1239 return ( $total, \@acctlines,$numlines);
1242 =head2 GetMemberAccountBalance
1244 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1246 Calculates amount immediately owing by the patron - non-issue charges.
1247 Based on GetMemberAccountRecords.
1248 Charges exempt from non-issue are:
1250 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1251 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1255 sub GetMemberAccountBalance {
1256 my ($borrowernumber) = @_;
1258 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1260 my @not_fines = ('Res');
1261 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1262 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1263 my $dbh = C4::Context->dbh;
1264 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1265 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1267 my %not_fine = map {$_ => 1} @not_fines;
1269 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1270 my $other_charges = 0;
1271 foreach (@$acctlines) {
1272 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1275 return ( $total, $total - $other_charges, $other_charges);
1278 =head2 GetBorNotifyAcctRecord
1280 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1282 Looks up accounting data for the patron with the given borrowernumber per file number.
1284 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1285 reference-to-array, where each element is a reference-to-hash; the
1286 keys are the fields of the C<accountlines> table in the Koha database.
1287 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1288 total amount outstanding for all of the account lines.
1292 sub GetBorNotifyAcctRecord {
1293 my ( $borrowernumber, $notifyid ) = @_;
1294 my $dbh = C4::Context->dbh;
1297 my $sth = $dbh->prepare(
1300 WHERE borrowernumber=?
1302 AND amountoutstanding != '0'
1303 ORDER BY notify_id,accounttype
1306 $sth->execute( $borrowernumber, $notifyid );
1308 while ( my $data = $sth->fetchrow_hashref ) {
1309 if ( $data->{itemnumber} ) {
1310 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1311 $data->{biblionumber} = $biblio->{biblionumber};
1312 $data->{title} = $biblio->{title};
1314 $acctlines[$numlines] = $data;
1316 $total += int(100 * $data->{'amountoutstanding'});
1319 return ( $total, \@acctlines, $numlines );
1322 =head2 checkuniquemember (OUEST-PROVENCE)
1324 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1326 Checks that a member exists or not in the database.
1328 C<&result> is nonzero (=exist) or 0 (=does not exist)
1329 C<&categorycode> is from categorycode table
1330 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1331 C<&surname> is the surname
1332 C<&firstname> is the firstname (only if collectivity=0)
1333 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1337 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1338 # This is especially true since first name is not even a required field.
1340 sub checkuniquemember {
1341 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1342 my $dbh = C4::Context->dbh;
1343 my $request = ($collectivity) ?
1344 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1346 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1347 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1348 my $sth = $dbh->prepare($request);
1349 if ($collectivity) {
1350 $sth->execute( uc($surname) );
1351 } elsif($dateofbirth){
1352 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1354 $sth->execute( uc($surname), ucfirst($firstname));
1356 my @data = $sth->fetchrow;
1357 ( $data[0] ) and return $data[0], $data[1];
1361 sub checkcardnumber {
1362 my ( $cardnumber, $borrowernumber ) = @_;
1364 # If cardnumber is null, we assume they're allowed.
1365 return 0 unless defined $cardnumber;
1367 my $dbh = C4::Context->dbh;
1368 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1369 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1370 my $sth = $dbh->prepare($query);
1373 ( $borrowernumber ? $borrowernumber : () )
1376 return 1 if $sth->fetchrow_hashref;
1378 my ( $min_length, $max_length ) = get_cardnumber_length();
1380 if length $cardnumber > $max_length
1381 or length $cardnumber < $min_length;
1386 =head2 get_cardnumber_length
1388 my ($min, $max) = C4::Members::get_cardnumber_length()
1390 Returns the minimum and maximum length for patron cardnumbers as
1391 determined by the CardnumberLength system preference, the
1392 BorrowerMandatoryField system preference, and the width of the
1397 sub get_cardnumber_length {
1398 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1399 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1400 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1401 # Is integer and length match
1402 if ( $cardnumber_length =~ m|^\d+$| ) {
1403 $min = $max = $cardnumber_length
1404 if $cardnumber_length >= $min
1405 and $cardnumber_length <= $max;
1407 # Else assuming it is a range
1408 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1409 $min = $1 if $1 and $min < $1;
1410 $max = $2 if $2 and $max > $2;
1414 return ( $min, $max );
1417 =head2 getzipnamecity (OUEST-PROVENCE)
1419 take all info from table city for the fields city and zip
1420 check for the name and the zip code of the city selected
1424 sub getzipnamecity {
1426 my $dbh = C4::Context->dbh;
1429 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1430 $sth->execute($cityid);
1431 my @data = $sth->fetchrow;
1432 return $data[0], $data[1], $data[2], $data[3];
1436 =head2 getdcity (OUEST-PROVENCE)
1438 recover cityid with city_name condition
1443 my ($city_name) = @_;
1444 my $dbh = C4::Context->dbh;
1445 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1446 $sth->execute($city_name);
1447 my $data = $sth->fetchrow;
1451 =head2 GetFirstValidEmailAddress
1453 $email = GetFirstValidEmailAddress($borrowernumber);
1455 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1456 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1461 sub GetFirstValidEmailAddress {
1462 my $borrowernumber = shift;
1463 my $dbh = C4::Context->dbh;
1464 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1465 $sth->execute( $borrowernumber );
1466 my $data = $sth->fetchrow_hashref;
1468 if ($data->{'email'}) {
1469 return $data->{'email'};
1470 } elsif ($data->{'emailpro'}) {
1471 return $data->{'emailpro'};
1472 } elsif ($data->{'B_email'}) {
1473 return $data->{'B_email'};
1479 =head2 GetNoticeEmailAddress
1481 $email = GetNoticeEmailAddress($borrowernumber);
1483 Return the email address of borrower used for notices, given the borrowernumber.
1484 Returns the empty string if no email address.
1488 sub GetNoticeEmailAddress {
1489 my $borrowernumber = shift;
1491 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1492 # if syspref is set to 'first valid' (value == OFF), look up email address
1493 if ( $which_address eq 'OFF' ) {
1494 return GetFirstValidEmailAddress($borrowernumber);
1496 # specified email address field
1497 my $dbh = C4::Context->dbh;
1498 my $sth = $dbh->prepare( qq{
1499 SELECT $which_address AS primaryemail
1501 WHERE borrowernumber=?
1503 $sth->execute($borrowernumber);
1504 my $data = $sth->fetchrow_hashref;
1505 return $data->{'primaryemail'} || '';
1508 =head2 GetExpiryDate
1510 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1512 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1513 Return date is also in ISO format.
1518 my ( $categorycode, $dateenrolled ) = @_;
1520 if ($categorycode) {
1521 my $dbh = C4::Context->dbh;
1522 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1523 $sth->execute($categorycode);
1524 $enrolments = $sth->fetchrow_hashref;
1526 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1527 my @date = split (/-/,$dateenrolled);
1528 if($enrolments->{enrolmentperiod}){
1529 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1531 return $enrolments->{enrolmentperioddate};
1535 =head2 GetborCatFromCatType
1537 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1539 Looks up the different types of borrowers in the database. Returns two
1540 elements: a reference-to-array, which lists the borrower category
1541 codes, and a reference-to-hash, which maps the borrower category codes
1542 to category descriptions.
1547 sub GetborCatFromCatType {
1548 my ( $category_type, $action, $no_branch_limit ) = @_;
1550 my $branch_limit = $no_branch_limit
1552 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1554 # FIXME - This API seems both limited and dangerous.
1555 my $dbh = C4::Context->dbh;
1558 SELECT categories.categorycode, categories.description
1562 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1565 $request .= " $action ";
1566 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1568 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1570 $request .= " ORDER BY categorycode";
1572 my $sth = $dbh->prepare($request);
1574 $action ? $category_type : (),
1575 $branch_limit ? $branch_limit : ()
1581 while ( my $data = $sth->fetchrow_hashref ) {
1582 push @codes, $data->{'categorycode'};
1583 $labels{ $data->{'categorycode'} } = $data->{'description'};
1586 return ( \@codes, \%labels );
1589 =head2 GetBorrowercategory
1591 $hashref = &GetBorrowercategory($categorycode);
1593 Given the borrower's category code, the function returns the corresponding
1594 data hashref for a comprehensive information display.
1598 sub GetBorrowercategory {
1600 my $dbh = C4::Context->dbh;
1604 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1606 WHERE categorycode = ?"
1608 $sth->execute($catcode);
1610 $sth->fetchrow_hashref;
1614 } # sub getborrowercategory
1617 =head2 GetBorrowerCategorycode
1619 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1621 Given the borrowernumber, the function returns the corresponding categorycode
1624 sub GetBorrowerCategorycode {
1625 my ( $borrowernumber ) = @_;
1626 my $dbh = C4::Context->dbh;
1627 my $sth = $dbh->prepare( qq{
1630 WHERE borrowernumber = ?
1632 $sth->execute( $borrowernumber );
1633 return $sth->fetchrow;
1636 =head2 GetBorrowercategoryList
1638 $arrayref_hashref = &GetBorrowercategoryList;
1639 If no category code provided, the function returns all the categories.
1643 sub GetBorrowercategoryList {
1644 my $no_branch_limit = @_ ? shift : 0;
1645 my $branch_limit = $no_branch_limit
1647 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1648 my $dbh = C4::Context->dbh;
1649 my $query = "SELECT categories.* FROM categories";
1651 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1652 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1654 $query .= " ORDER BY description";
1655 my $sth = $dbh->prepare( $query );
1656 $sth->execute( $branch_limit ? $branch_limit : () );
1657 my $data = $sth->fetchall_arrayref( {} );
1660 } # sub getborrowercategory
1662 =head2 ethnicitycategories
1664 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1666 Looks up the different ethnic types in the database. Returns two
1667 elements: a reference-to-array, which lists the ethnicity codes, and a
1668 reference-to-hash, which maps the ethnicity codes to ethnicity
1675 sub ethnicitycategories {
1676 my $dbh = C4::Context->dbh;
1677 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1681 while ( my $data = $sth->fetchrow_hashref ) {
1682 push @codes, $data->{'code'};
1683 $labels{ $data->{'code'} } = $data->{'name'};
1685 return ( \@codes, \%labels );
1690 $ethn_name = &fixEthnicity($ethn_code);
1692 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1693 corresponding descriptive name from the C<ethnicity> table in the
1694 Koha database ("European" or "Pacific Islander").
1701 my $ethnicity = shift;
1702 return unless $ethnicity;
1703 my $dbh = C4::Context->dbh;
1704 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1705 $sth->execute($ethnicity);
1706 my $data = $sth->fetchrow_hashref;
1707 return $data->{'name'};
1708 } # sub fixEthnicity
1712 $dateofbirth,$date = &GetAge($date);
1714 this function return the borrowers age with the value of dateofbirth
1720 my ( $date, $date_ref ) = @_;
1722 if ( not defined $date_ref ) {
1723 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1726 my ( $year1, $month1, $day1 ) = split /-/, $date;
1727 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1729 my $age = $year2 - $year1;
1730 if ( $month1 . $day1 > $month2 . $day2 ) {
1739 $cityarrayref = GetCities();
1741 Returns an array_ref of the entries in the cities table
1742 If there are entries in the table an empty row is returned
1743 This is currently only used to populate a popup in memberentry
1749 my $dbh = C4::Context->dbh;
1750 my $city_arr = $dbh->selectall_arrayref(
1751 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1753 if ( @{$city_arr} ) {
1754 unshift @{$city_arr}, {
1755 city_zipcode => q{},
1759 city_country => q{},
1766 =head2 GetSortDetails (OUEST-PROVENCE)
1768 ($lib) = &GetSortDetails($category,$sortvalue);
1770 Returns the authorized value details
1771 C<&$lib>return value of authorized value details
1772 C<&$sortvalue>this is the value of authorized value
1773 C<&$category>this is the value of authorized value category
1777 sub GetSortDetails {
1778 my ( $category, $sortvalue ) = @_;
1779 my $dbh = C4::Context->dbh;
1780 my $query = qq|SELECT lib
1781 FROM authorised_values
1783 AND authorised_value=? |;
1784 my $sth = $dbh->prepare($query);
1785 $sth->execute( $category, $sortvalue );
1786 my $lib = $sth->fetchrow;
1787 return ($lib) if ($lib);
1788 return ($sortvalue) unless ($lib);
1791 =head2 MoveMemberToDeleted
1793 $result = &MoveMemberToDeleted($borrowernumber);
1795 Copy the record from borrowers to deletedborrowers table.
1799 # FIXME: should do it in one SQL statement w/ subquery
1800 # Otherwise, we should return the @data on success
1802 sub MoveMemberToDeleted {
1803 my ($member) = shift or return;
1804 my $dbh = C4::Context->dbh;
1805 my $query = qq|SELECT *
1807 WHERE borrowernumber=?|;
1808 my $sth = $dbh->prepare($query);
1809 $sth->execute($member);
1810 my @data = $sth->fetchrow_array;
1811 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1813 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1814 . ( "?," x ( scalar(@data) - 1 ) )
1816 $sth->execute(@data);
1821 DelMember($borrowernumber);
1823 This function remove directly a borrower whitout writing it on deleteborrower.
1824 + Deletes reserves for the borrower
1829 my $dbh = C4::Context->dbh;
1830 my $borrowernumber = shift;
1831 #warn "in delmember with $borrowernumber";
1832 return unless $borrowernumber; # borrowernumber is mandatory.
1834 my $query = qq|DELETE
1836 WHERE borrowernumber=?|;
1837 my $sth = $dbh->prepare($query);
1838 $sth->execute($borrowernumber);
1842 WHERE borrowernumber = ?
1844 $sth = $dbh->prepare($query);
1845 $sth->execute($borrowernumber);
1846 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1850 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1852 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1854 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1859 sub ExtendMemberSubscriptionTo {
1860 my ( $borrowerid,$date) = @_;
1861 my $dbh = C4::Context->dbh;
1862 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1864 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1865 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1866 C4::Dates->new()->output("iso");
1867 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1869 my $sth = $dbh->do(<<EOF);
1871 SET dateexpiry='$date'
1872 WHERE borrowernumber='$borrowerid'
1875 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1877 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1878 return $date if ($sth);
1882 =head2 GetTitles (OUEST-PROVENCE)
1884 ($borrowertitle)= &GetTitles();
1886 Looks up the different title . Returns array with all borrowers title
1891 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1892 unshift( @borrowerTitle, "" );
1893 my $count=@borrowerTitle;
1898 return ( \@borrowerTitle);
1902 =head2 GetPatronImage
1904 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1906 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1910 sub GetPatronImage {
1911 my ($borrowernumber) = @_;
1912 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1913 my $dbh = C4::Context->dbh;
1914 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1915 my $sth = $dbh->prepare($query);
1916 $sth->execute($borrowernumber);
1917 my $imagedata = $sth->fetchrow_hashref;
1918 warn "Database error!" if $sth->errstr;
1919 return $imagedata, $sth->errstr;
1922 =head2 PutPatronImage
1924 PutPatronImage($cardnumber, $mimetype, $imgfile);
1926 Stores patron binary image data and mimetype in database.
1927 NOTE: This function is good for updating images as well as inserting new images in the database.
1931 sub PutPatronImage {
1932 my ($cardnumber, $mimetype, $imgfile) = @_;
1933 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1934 my $dbh = C4::Context->dbh;
1935 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1936 my $sth = $dbh->prepare($query);
1937 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1938 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1939 return $sth->errstr;
1942 =head2 RmPatronImage
1944 my ($dberror) = RmPatronImage($borrowernumber);
1946 Removes the image for the patron with the supplied borrowernumber.
1951 my ($borrowernumber) = @_;
1952 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1953 my $dbh = C4::Context->dbh;
1954 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1955 my $sth = $dbh->prepare($query);
1956 $sth->execute($borrowernumber);
1957 my $dberror = $sth->errstr;
1958 warn "Database error!" if $sth->errstr;
1962 =head2 GetHideLostItemsPreference
1964 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1966 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1967 C<&$hidelostitemspref>return value of function, 0 or 1
1971 sub GetHideLostItemsPreference {
1972 my ($borrowernumber) = @_;
1973 my $dbh = C4::Context->dbh;
1974 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1975 my $sth = $dbh->prepare($query);
1976 $sth->execute($borrowernumber);
1977 my $hidelostitems = $sth->fetchrow;
1978 return $hidelostitems;
1981 =head2 GetBorrowersToExpunge
1983 $borrowers = &GetBorrowersToExpunge(
1984 not_borrowered_since => $not_borrowered_since,
1985 expired_before => $expired_before,
1986 category_code => $category_code,
1987 branchcode => $branchcode
1990 This function get all borrowers based on the given criteria.
1994 sub GetBorrowersToExpunge {
1997 my $filterdate = $params->{'not_borrowered_since'};
1998 my $filterexpiry = $params->{'expired_before'};
1999 my $filtercategory = $params->{'category_code'};
2000 my $filterbranch = $params->{'branchcode'} ||
2001 ((C4::Context->preference('IndependentBranches')
2002 && C4::Context->userenv
2003 && !C4::Context->IsSuperLibrarian()
2004 && C4::Context->userenv->{branch})
2005 ? C4::Context->userenv->{branch}
2008 my $dbh = C4::Context->dbh;
2010 SELECT borrowers.borrowernumber,
2011 MAX(old_issues.timestamp) AS latestissue,
2012 MAX(issues.timestamp) AS currentissue
2014 JOIN categories USING (categorycode)
2015 LEFT JOIN old_issues USING (borrowernumber)
2016 LEFT JOIN issues USING (borrowernumber)
2017 WHERE category_type <> 'S'
2018 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
2021 if ( $filterbranch && $filterbranch ne "" ) {
2022 $query.= " AND borrowers.branchcode = ? ";
2023 push( @query_params, $filterbranch );
2025 if ( $filterexpiry ) {
2026 $query .= " AND dateexpiry < ? ";
2027 push( @query_params, $filterexpiry );
2029 if ( $filtercategory ) {
2030 $query .= " AND categorycode = ? ";
2031 push( @query_params, $filtercategory );
2033 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2034 if ( $filterdate ) {
2035 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2036 push @query_params,$filterdate;
2038 warn $query if $debug;
2040 my $sth = $dbh->prepare($query);
2041 if (scalar(@query_params)>0){
2042 $sth->execute(@query_params);
2049 while ( my $data = $sth->fetchrow_hashref ) {
2050 push @results, $data;
2055 =head2 GetBorrowersWhoHaveNeverBorrowed
2057 $results = &GetBorrowersWhoHaveNeverBorrowed
2059 This function get all borrowers who have never borrowed.
2061 I<$result> is a ref to an array which all elements are a hasref.
2065 sub GetBorrowersWhoHaveNeverBorrowed {
2066 my $filterbranch = shift ||
2067 ((C4::Context->preference('IndependentBranches')
2068 && C4::Context->userenv
2069 && !C4::Context->IsSuperLibrarian()
2070 && C4::Context->userenv->{branch})
2071 ? C4::Context->userenv->{branch}
2073 my $dbh = C4::Context->dbh;
2075 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2077 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2078 WHERE issues.borrowernumber IS NULL
2081 if ($filterbranch && $filterbranch ne ""){
2082 $query.=" AND borrowers.branchcode= ?";
2083 push @query_params,$filterbranch;
2085 warn $query if $debug;
2087 my $sth = $dbh->prepare($query);
2088 if (scalar(@query_params)>0){
2089 $sth->execute(@query_params);
2096 while ( my $data = $sth->fetchrow_hashref ) {
2097 push @results, $data;
2102 =head2 GetBorrowersWithIssuesHistoryOlderThan
2104 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2106 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2108 I<$result> is a ref to an array which all elements are a hashref.
2109 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2113 sub GetBorrowersWithIssuesHistoryOlderThan {
2114 my $dbh = C4::Context->dbh;
2115 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2116 my $filterbranch = shift ||
2117 ((C4::Context->preference('IndependentBranches')
2118 && C4::Context->userenv
2119 && !C4::Context->IsSuperLibrarian()
2120 && C4::Context->userenv->{branch})
2121 ? C4::Context->userenv->{branch}
2124 SELECT count(borrowernumber) as n,borrowernumber
2126 WHERE returndate < ?
2127 AND borrowernumber IS NOT NULL
2130 push @query_params, $date;
2132 $query.=" AND branchcode = ?";
2133 push @query_params, $filterbranch;
2135 $query.=" GROUP BY borrowernumber ";
2136 warn $query if $debug;
2137 my $sth = $dbh->prepare($query);
2138 $sth->execute(@query_params);
2141 while ( my $data = $sth->fetchrow_hashref ) {
2142 push @results, $data;
2147 =head2 GetBorrowersNamesAndLatestIssue
2149 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2151 this function get borrowers Names and surnames and Issue information.
2153 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2154 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2158 sub GetBorrowersNamesAndLatestIssue {
2159 my $dbh = C4::Context->dbh;
2160 my @borrowernumbers=@_;
2162 SELECT surname,lastname, phone, email,max(timestamp)
2164 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2165 GROUP BY borrowernumber
2167 my $sth = $dbh->prepare($query);
2169 my $results = $sth->fetchall_arrayref({});
2177 my $success = ModPrivacy( $borrowernumber, $privacy );
2179 Update the privacy of a patron.
2182 true on success, false on failure
2189 my $borrowernumber = shift;
2190 my $privacy = shift;
2191 return unless defined $borrowernumber;
2192 return unless $borrowernumber =~ /^\d+$/;
2194 return ModMember( borrowernumber => $borrowernumber,
2195 privacy => $privacy );
2200 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2202 Adds a message to the messages table for the given borrower.
2211 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2213 my $dbh = C4::Context->dbh;
2215 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2219 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2220 my $sth = $dbh->prepare($query);
2221 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2222 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2228 GetMessages( $borrowernumber, $type );
2230 $type is message type, B for borrower, or L for Librarian.
2231 Empty type returns all messages of any type.
2233 Returns all messages for the given borrowernumber
2238 my ( $borrowernumber, $type, $branchcode ) = @_;
2244 my $dbh = C4::Context->dbh;
2247 branches.branchname,
2250 messages.branchcode LIKE '$branchcode' AS can_delete
2251 FROM messages, branches
2252 WHERE borrowernumber = ?
2253 AND message_type LIKE ?
2254 AND messages.branchcode = branches.branchcode
2255 ORDER BY message_date DESC";
2256 my $sth = $dbh->prepare($query);
2257 $sth->execute( $borrowernumber, $type ) ;
2260 while ( my $data = $sth->fetchrow_hashref ) {
2261 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2262 $data->{message_date_formatted} = $d->output;
2263 push @results, $data;
2271 GetMessagesCount( $borrowernumber, $type );
2273 $type is message type, B for borrower, or L for Librarian.
2274 Empty type returns all messages of any type.
2276 Returns the number of messages for the given borrowernumber
2280 sub GetMessagesCount {
2281 my ( $borrowernumber, $type, $branchcode ) = @_;
2287 my $dbh = C4::Context->dbh;
2289 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2290 my $sth = $dbh->prepare($query);
2291 $sth->execute( $borrowernumber, $type ) ;
2294 my $data = $sth->fetchrow_hashref;
2295 my $count = $data->{'MsgCount'};
2302 =head2 DeleteMessage
2304 DeleteMessage( $message_id );
2309 my ( $message_id ) = @_;
2311 my $dbh = C4::Context->dbh;
2312 my $query = "SELECT * FROM messages WHERE message_id = ?";
2313 my $sth = $dbh->prepare($query);
2314 $sth->execute( $message_id );
2315 my $message = $sth->fetchrow_hashref();
2317 $query = "DELETE FROM messages WHERE message_id = ?";
2318 $sth = $dbh->prepare($query);
2319 $sth->execute( $message_id );
2320 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2325 IssueSlip($branchcode, $borrowernumber, $quickslip)
2327 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2329 $quickslip is boolean, to indicate whether we want a quick slip
2334 my ($branch, $borrowernumber, $quickslip) = @_;
2336 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2338 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2340 my $issueslist = GetPendingIssues($borrowernumber);
2341 foreach my $it (@$issueslist){
2342 if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) {
2345 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2346 $it->{'overdue'} = 1;
2348 my $dt = dt_from_string( $it->{'date_due'} );
2349 $it->{'date_due'} = output_pref( $dt );;
2351 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2353 my ($letter_code, %repeat);
2355 $letter_code = 'ISSUEQSLIP';
2357 'checkedout' => [ map {
2361 }, grep { $_->{'now'} } @issues ],
2365 $letter_code = 'ISSUESLIP';
2367 'checkedout' => [ map {
2371 }, grep { !$_->{'overdue'} } @issues ],
2373 'overdue' => [ map {
2377 }, grep { $_->{'overdue'} } @issues ],
2380 $_->{'timestamp'} = $_->{'newdate'};
2382 } @{ GetNewsToDisplay("slip",$branch) } ],
2386 return C4::Letters::GetPreparedLetter (
2387 module => 'circulation',
2388 letter_code => $letter_code,
2389 branchcode => $branch,
2391 'branches' => $branch,
2392 'borrowers' => $borrowernumber,
2398 =head2 GetBorrowersWithEmail
2400 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2402 This gets a list of users and their basic details from their email address.
2403 As it's possible for multiple user to have the same email address, it provides
2404 you with all of them. If there is no userid for the user, there will be an
2405 C<undef> there. An empty list will be returned if there are no matches.
2409 sub GetBorrowersWithEmail {
2412 my $dbh = C4::Context->dbh;
2414 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2415 my $sth=$dbh->prepare($query);
2416 $sth->execute($email);
2418 while (my $ref = $sth->fetch) {
2421 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2425 sub AddMember_Opac {
2426 my ( %borrower ) = @_;
2428 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2430 my $sr = new String::Random;
2431 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2432 my $password = $sr->randpattern("AAAAAAAAAA");
2433 $borrower{'password'} = $password;
2435 $borrower{'cardnumber'} = fixup_cardnumber();
2437 my $borrowernumber = AddMember(%borrower);
2439 return ( $borrowernumber, $password );
2442 =head2 AddEnrolmentFeeIfNeeded
2444 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2446 Add enrolment fee for a patron if needed.
2450 sub AddEnrolmentFeeIfNeeded {
2451 my ( $categorycode, $borrowernumber ) = @_;
2452 # check for enrollment fee & add it if needed
2453 my $dbh = C4::Context->dbh;
2454 my $sth = $dbh->prepare(q{
2457 WHERE categorycode=?
2459 $sth->execute( $categorycode );
2461 warn sprintf('Database returned the following error: %s', $sth->errstr);
2464 my ($enrolmentfee) = $sth->fetchrow;
2465 if ($enrolmentfee && $enrolmentfee > 0) {
2466 # insert fee in patron debts
2467 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2472 my ( $borrowernumber ) = @_;
2474 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2475 my $sth = C4::Context->dbh->prepare( $sql );
2476 $sth->execute( $borrowernumber );
2477 my ( $count ) = $sth->fetchrow_array();
2482 END { } # module clean-up code here (global destructor)