3 # Copyright 2000-2003 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
32 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
36 $debug = $ENV{DEBUG} || 0;
47 &GetMemberIssuesAndFines
66 &GetMemberAccountRecords
67 &GetBorNotifyAcctRecord
71 &GetBorrowercategoryList
73 &GetBorrowersWhoHaveNotBorrowedSince
74 &GetBorrowersWhoHaveNeverBorrowed
75 &GetBorrowersWithIssuesHistoryOlderThan
98 &ExtendMemberSubscriptionTo
116 C4::Members - Perl Module containing convenience functions for member handling
124 This module contains routines for adding, modifying and deleting members/patrons/borrowers
132 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
136 Looks up patrons (borrowers) by name.
138 BUGFIX 499: C<$type> is now used to determine type of search.
139 if $type is "simple", search is performed on the first letter of the
142 $category_type is used to get a specified type of user.
143 (mainly adults when creating a child.)
145 C<$searchstring> is a space-separated list of search terms. Each term
146 must match the beginning a borrower's surname, first name, or other
149 C<$filter> is assumed to be a list of elements to filter results on
151 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
153 C<&SearchMember> returns a two-element list. C<$borrowers> is a
154 reference-to-array; each element is a reference-to-hash, whose keys
155 are the fields of the C<borrowers> table in the Koha database.
156 C<$count> is the number of elements in C<$borrowers>.
161 #used by member enquiries from the intranet
162 #called by member.pl and circ/circulation.pl
164 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
165 my $dbh = C4::Context->dbh;
171 # this is used by circulation everytime a new borrowers cardnumber is scanned
172 # so we can check an exact match first, if that works return, otherwise do the rest
173 $query = "SELECT * FROM borrowers
174 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
176 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
177 $sth->execute($searchstring);
178 my $data = $sth->fetchall_arrayref({});
180 return ( scalar(@$data), $data );
184 if ( $type eq "simple" ) # simple search for one letter only
186 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
187 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
188 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
189 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
190 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
193 $query.=" ORDER BY $orderby";
194 @bind = ("$searchstring%","$searchstring");
196 else # advanced search looking in surname, firstname and othernames
198 @data = split( ' ', $searchstring );
201 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
202 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
203 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
206 $query.="((surname LIKE ? OR surname LIKE ?
207 OR firstname LIKE ? OR firstname LIKE ?
208 OR othernames LIKE ? OR othernames LIKE ?)
210 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
212 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
213 "$data[0]%", "% $data[0]%"
215 for ( my $i = 1 ; $i < $count ; $i++ ) {
216 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
217 OR firstname LIKE ? OR firstname LIKE ?
218 OR othernames LIKE ? OR othernames LIKE ?)";
220 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
221 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
225 $query = $query . ") OR cardnumber LIKE ? ";
226 push( @bind, $searchstring );
227 if (C4::Context->preference('ExtendedPatronAttributes')) {
228 $query .= "OR borrowernumber IN (
229 SELECT borrowernumber
230 FROM borrower_attributes
231 JOIN borrower_attribute_types USING (code)
232 WHERE staff_searchable = 1
235 push (@bind, $searchstring);
237 $query .= "order by $orderby";
242 $sth = $dbh->prepare($query);
244 $debug and print STDERR "Q $orderby : $query\n";
245 $sth->execute(@bind);
247 $data = $sth->fetchall_arrayref({});
250 return ( scalar(@$data), $data );
253 =head2 GetMemberDetails
255 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
257 Looks up a patron and returns information about him or her. If
258 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
259 up the borrower by number; otherwise, it looks up the borrower by card
262 C<$borrower> is a reference-to-hash whose keys are the fields of the
263 borrowers table in the Koha database. In addition,
264 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
265 about the patron. Its keys act as flags :
267 if $borrower->{flags}->{LOST} {
268 # Patron's card was reported lost
271 Each flag has a C<message> key, giving a human-readable explanation of
272 the flag. If the state of a flag means that the patron should not be
273 allowed to borrow any more books, then it will have a C<noissues> key
276 The possible flags are:
282 =item Shows the patron's credit or debt, if any.
290 =item (Gone, no address.) Set if the patron has left without giving a
299 =item Set if the patron's card has been reported as lost.
307 =item Set if the patron has been debarred.
315 =item Any additional notes about the patron.
323 =item Set if the patron has overdue items. This flag has several keys:
325 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
326 overdue items. Its elements are references-to-hash, each describing an
327 overdue item. The keys are selected fields from the issues, biblio,
328 biblioitems, and items tables of the Koha database.
330 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
331 the overdue items, one per line.
339 =item Set if any items that the patron has reserved are available.
341 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
342 available items. Each element is a reference-to-hash whose keys are
343 fields from the reserves table of the Koha database.
347 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
348 about the top-level permissions flags set for the borrower. For example,
349 if a user has the "editcatalogue" permission,
350 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
355 sub GetMemberDetails {
356 my ( $borrowernumber, $cardnumber ) = @_;
357 my $dbh = C4::Context->dbh;
360 if ($borrowernumber) {
361 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
362 $sth->execute($borrowernumber);
364 elsif ($cardnumber) {
365 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
366 $sth->execute($cardnumber);
371 my $borrower = $sth->fetchrow_hashref;
372 my ($amount) = GetMemberAccountRecords( $borrowernumber);
373 $borrower->{'amountoutstanding'} = $amount;
374 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
375 my $flags = patronflags( $borrower);
378 $sth = $dbh->prepare("select bit,flag from userflags");
380 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
381 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
382 $accessflagshash->{$flag} = 1;
386 $borrower->{'flags'} = $flags;
387 $borrower->{'authflags'} = $accessflagshash;
389 # find out how long the membership lasts
392 "select enrolmentperiod from categories where categorycode = ?");
393 $sth->execute( $borrower->{'categorycode'} );
394 my $enrolment = $sth->fetchrow;
395 $borrower->{'enrolmentperiod'} = $enrolment;
396 return ($borrower); #, $flags, $accessflagshash);
403 NOTE!: If you change this function, be sure to update the POD for
406 $flags = &patronflags($patron);
409 {message} Message showing patron's credit or debt
410 {noissues} Set if patron owes >$5.00
411 {GNA} Set if patron gone w/o address
412 {message} "Borrower has no valid address"
414 {LOST} Set if patron's card reported lost
415 {message} Message to this effect
417 {DBARRED} Set is patron is debarred
418 {message} Message to this effect
420 {NOTES} Set if patron has notes
421 {message} Notes about patron
422 {ODUES} Set if patron has overdue books
424 {itemlist} ref-to-array: list of overdue books
425 {itemlisttext} Text list of overdue items
426 {WAITING} Set if there are items available that the
428 {message} Message to this effect
429 {itemlist} ref-to-array: list of available items
432 # FIXME rename this function.
435 my ( $patroninformation) = @_;
436 my $dbh=C4::Context->dbh;
437 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
440 my $noissuescharge = C4::Context->preference("noissuescharge");
441 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
442 $flaginfo{'amount'} = sprintf "%.02f",$amount;
443 if ( $amount > $noissuescharge ) {
444 $flaginfo{'noissues'} = 1;
446 $flags{'CHARGES'} = \%flaginfo;
448 elsif ( $amount < 0 ) {
450 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
451 $flags{'CREDITS'} = \%flaginfo;
453 if ( $patroninformation->{'gonenoaddress'}
454 && $patroninformation->{'gonenoaddress'} == 1 )
457 $flaginfo{'message'} = 'Borrower has no valid address.';
458 $flaginfo{'noissues'} = 1;
459 $flags{'GNA'} = \%flaginfo;
461 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
463 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
464 $flaginfo{'noissues'} = 1;
465 $flags{'LOST'} = \%flaginfo;
467 if ( $patroninformation->{'debarred'}
468 && $patroninformation->{'debarred'} == 1 )
471 $flaginfo{'message'} = 'Borrower is Debarred.';
472 $flaginfo{'noissues'} = 1;
473 $flags{'DBARRED'} = \%flaginfo;
475 if ( $patroninformation->{'borrowernotes'}
476 && $patroninformation->{'borrowernotes'} )
479 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
480 $flags{'NOTES'} = \%flaginfo;
482 my ( $odues, $itemsoverdue ) =
483 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
486 $flaginfo{'message'} = "Yes";
487 $flaginfo{'itemlist'} = $itemsoverdue;
488 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
491 $flaginfo{'itemlisttext'} .=
492 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
494 $flags{'ODUES'} = \%flaginfo;
496 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
497 my $nowaiting = scalar @itemswaiting;
498 if ( $nowaiting > 0 ) {
500 $flaginfo{'message'} = "Reserved items available";
501 $flaginfo{'itemlist'} = \@itemswaiting;
502 $flags{'WAITING'} = \%flaginfo;
510 $borrower = &GetMember($information, $type);
512 Looks up information about a patron (borrower) by either card number
513 ,firstname, or borrower number, depending on $type value.
514 If C<$type> == 'cardnumber', C<&GetBorrower>
515 searches by cardnumber then by firstname if not found in cardnumber;
516 otherwise, it searches by borrowernumber.
518 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
519 the C<borrowers> table in the Koha database.
525 my ( $information, $type ) = @_;
526 my $dbh = C4::Context->dbh;
529 SELECT borrowers.*, categories.category_type, categories.description
531 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
533 if (defined($type) and ( $type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber' ) ){
534 $information = uc $information;
535 $sth = $dbh->prepare("$select WHERE $type=?");
537 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
539 $sth->execute($information);
540 my $data = $sth->fetchrow_hashref;
541 ($data) and return ($data);
543 if (defined($type) and ($type eq 'cardnumber' || $type eq 'firstname')) { # otherwise, try with firstname
544 $sth = $dbh->prepare("$select WHERE firstname like ?");
545 $sth->execute($information);
546 $data = $sth->fetchrow_hashref;
547 ($data) and return ($data);
552 =head2 GetMemberIssuesAndFines
554 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
556 Returns aggregate data about items borrowed by the patron with the
557 given borrowernumber.
559 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
560 number of overdue items the patron currently has borrowed. C<$issue_count> is the
561 number of books the patron currently has borrowed. C<$total_fines> is
562 the total fine currently due by the borrower.
567 sub GetMemberIssuesAndFines {
568 my ( $borrowernumber ) = @_;
569 my $dbh = C4::Context->dbh;
570 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
572 $debug and warn $query."\n";
573 my $sth = $dbh->prepare($query);
574 $sth->execute($borrowernumber);
575 my $issue_count = $sth->fetchrow_arrayref->[0];
578 $sth = $dbh->prepare(
579 "SELECT COUNT(*) FROM issues
580 WHERE borrowernumber = ?
581 AND date_due < now()"
583 $sth->execute($borrowernumber);
584 my $overdue_count = $sth->fetchrow_arrayref->[0];
587 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
588 $sth->execute($borrowernumber);
589 my $total_fines = $sth->fetchrow_arrayref->[0];
592 return ($overdue_count, $issue_count, $total_fines);
596 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
605 my $success = ModMember(borrowernumber => $borrowernumber, [ field => value ]... );
607 Modify borrower's data. All date fields should ALREADY be in ISO format.
610 true on success, or false on failure
618 my $dbh = C4::Context->dbh;
619 my $iso_re = C4::Dates->new()->regexp('iso');
620 foreach (qw(dateofbirth dateexpiry dateenrolled)) {
621 if (my $tempdate = $data{$_}) { # assignment, not comparison
622 ($tempdate =~ /$iso_re/) and next; # Congatulations, you sent a valid ISO date.
623 warn "ModMember given $_ not in ISO format ($tempdate)";
624 my $tempdate2 = format_date_in_iso($tempdate);
625 if (!$tempdate2 or $tempdate2 eq '0000-00-00') {
626 warn "ModMember cannot convert '$tempdate' (from syspref to ISO)";
629 $data{$_} = $tempdate2;
632 if (!$data{'dateofbirth'}){
633 delete $data{'dateofbirth'};
635 my @columns = &columns;
636 my %hashborrowerfields = (map {$_=>1} @columns);
637 my $query = "UPDATE borrowers SET \n";
641 # test to know if you must update or not the borrower password
642 if (exists $data{password}) {
643 if ($data{password} eq '****' or $data{password} eq '') {
644 delete $data{password};
646 $data{password} = md5_base64($data{password});
650 foreach (keys %data) {
651 next if ($_ eq 'borrowernumber' or $_ eq 'flags');
652 if ($hashborrowerfields{$_}){
654 push @parameters,$data{$_};
660 (@badkeys) and warn scalar(@badkeys) . " Illegal key(s) passed to ModMember: " . join(',',@badkeys);
662 $query .= " WHERE borrowernumber=?";
663 push @parameters, $data{'borrowernumber'};
664 $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
665 $sth = $dbh->prepare($query);
666 my $execute_success = $sth->execute(@parameters);
669 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
670 # so when we update information for an adult we should check for guarantees and update the relevant part
671 # of their records, ie addresses and phone numbers
672 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
673 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
674 # is adult check guarantees;
675 UpdateGuarantees(%data);
677 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})")
678 if C4::Context->preference("BorrowersLog");
680 return $execute_success;
688 $borrowernumber = &AddMember(%borrower);
690 insert new borrower into table
691 Returns the borrowernumber
698 my $dbh = C4::Context->dbh;
699 $data{'userid'} = '' unless $data{'password'};
700 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
702 # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
703 # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
704 # $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
705 # $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
706 # $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
707 # This query should be rewritten to use "?" at execute.
708 if (!$data{'dateofbirth'}){
709 undef ($data{'dateofbirth'});
712 "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
713 . ",surname=" . $dbh->quote( $data{'surname'} )
714 . ",firstname=" . $dbh->quote( $data{'firstname'} )
715 . ",title=" . $dbh->quote( $data{'title'} )
716 . ",othernames=" . $dbh->quote( $data{'othernames'} )
717 . ",initials=" . $dbh->quote( $data{'initials'} )
718 . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
719 . ",streettype=" . $dbh->quote( $data{'streettype'} )
720 . ",address=" . $dbh->quote( $data{'address'} )
721 . ",address2=" . $dbh->quote( $data{'address2'} )
722 . ",zipcode=" . $dbh->quote( $data{'zipcode'} )
723 . ",city=" . $dbh->quote( $data{'city'} )
724 . ",phone=" . $dbh->quote( $data{'phone'} )
725 . ",email=" . $dbh->quote( $data{'email'} )
726 . ",mobile=" . $dbh->quote( $data{'mobile'} )
727 . ",phonepro=" . $dbh->quote( $data{'phonepro'} )
728 . ",opacnote=" . $dbh->quote( $data{'opacnote'} )
729 . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
730 . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
731 . ",branchcode=" . $dbh->quote( $data{'branchcode'} )
732 . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
733 . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
734 . ",contactname=" . $dbh->quote( $data{'contactname'} )
735 . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
736 . ",dateexpiry=" . $dbh->quote( $data{'dateexpiry'} )
737 . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
738 . ",B_address=" . $dbh->quote( $data{'B_address'} )
739 . ",B_zipcode=" . $dbh->quote( $data{'B_zipcode'} )
740 . ",B_city=" . $dbh->quote( $data{'B_city'} )
741 . ",B_phone=" . $dbh->quote( $data{'B_phone'} )
742 . ",B_email=" . $dbh->quote( $data{'B_email'} )
743 . ",password=" . $dbh->quote( $data{'password'} )
744 . ",userid=" . $dbh->quote( $data{'userid'} )
745 . ",sort1=" . $dbh->quote( $data{'sort1'} )
746 . ",sort2=" . $dbh->quote( $data{'sort2'} )
747 . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
748 . ",emailpro=" . $dbh->quote( $data{'emailpro'} )
749 . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
750 . ",sex=" . $dbh->quote( $data{'sex'} )
751 . ",fax=" . $dbh->quote( $data{'fax'} )
752 . ",relationship=" . $dbh->quote( $data{'relationship'} )
753 . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
754 . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
755 . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
756 . ",lost=" . $dbh->quote( $data{'lost'} )
757 . ",debarred=" . $dbh->quote( $data{'debarred'} )
758 . ",ethnicity=" . $dbh->quote( $data{'ethnicity'} )
759 . ",ethnotes=" . $dbh->quote( $data{'ethnotes'} )
760 . ",altcontactsurname=" . $dbh->quote( $data{'altcontactsurname'} )
761 . ",altcontactfirstname=" . $dbh->quote( $data{'altcontactfirstname'} )
762 . ",altcontactaddress1=" . $dbh->quote( $data{'altcontactaddress1'} )
763 . ",altcontactaddress2=" . $dbh->quote( $data{'altcontactaddress2'} )
764 . ",altcontactaddress3=" . $dbh->quote( $data{'altcontactaddress3'} )
765 . ",altcontactzipcode=" . $dbh->quote( $data{'altcontactzipcode'} )
766 . ",altcontactphone=" . $dbh->quote( $data{'altcontactphone'} ) ;
767 $debug and print STDERR "AddMember SQL: ($query)\n";
768 my $sth = $dbh->prepare($query);
769 # print "Executing SQL: $query\n";
772 $data{'borrowernumber'} = $dbh->{'mysql_insertid'}; # unneeded w/ autoincrement ?
773 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
775 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
777 # check for enrollment fee & add it if needed
778 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
779 $sth->execute($data{'categorycode'});
780 my ($enrolmentfee) = $sth->fetchrow;
781 if ($enrolmentfee && $enrolmentfee > 0) {
782 # insert fee in patron debts
783 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
785 return $data{'borrowernumber'};
789 my ($uid,$member) = @_;
790 my $dbh = C4::Context->dbh;
791 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
792 # Then we need to tell the user and have them create a new one.
795 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
796 $sth->execute( $uid, $member );
797 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
805 sub Generate_Userid {
806 my ($borrowernumber, $firstname, $surname) = @_;
810 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
811 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
812 $newuid = lc("$firstname.$surname");
813 $newuid .= $offset unless $offset == 0;
816 } while (!Check_Userid($newuid,$borrowernumber));
822 my ( $uid, $member, $digest ) = @_;
823 my $dbh = C4::Context->dbh;
825 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
826 #Then we need to tell the user and have them create a new one.
830 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
831 $sth->execute( $uid, $member );
832 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
836 #Everything is good so we can update the information.
839 "update borrowers set userid=?, password=? where borrowernumber=?");
840 $sth->execute( $uid, $digest, $member );
844 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
850 =head2 fixup_cardnumber
852 Warning: The caller is responsible for locking the members table in write
853 mode, to avoid database corruption.
857 use vars qw( @weightings );
858 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
860 sub fixup_cardnumber ($) {
861 my ($cardnumber) = @_;
862 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
864 # Find out whether member numbers should be generated
865 # automatically. Should be either "1" or something else.
866 # Defaults to "0", which is interpreted as "no".
868 # if ($cardnumber !~ /\S/ && $autonumber_members) {
869 ($autonumber_members) or return $cardnumber;
870 my $checkdigit = C4::Context->preference('checkdigit');
871 my $dbh = C4::Context->dbh;
872 if ( $checkdigit and $checkdigit eq 'katipo' ) {
874 # if checkdigit is selected, calculate katipo-style cardnumber.
875 # otherwise, just use the max()
876 # purpose: generate checksum'd member numbers.
877 # We'll assume we just got the max value of digits 2-8 of member #'s
878 # from the database and our job is to increment that by one,
879 # determine the 1st and 9th digits and return the full string.
880 my $sth = $dbh->prepare(
881 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
884 my $data = $sth->fetchrow_hashref;
885 $cardnumber = $data->{new_num};
886 if ( !$cardnumber ) { # If DB has no values,
887 $cardnumber = 1000000; # start at 1000000
893 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
894 # read weightings, left to right, 1 char at a time
895 my $temp1 = $weightings[$i];
897 # sequence left to right, 1 char at a time
898 my $temp2 = substr( $cardnumber, $i, 1 );
900 # mult each char 1-7 by its corresponding weighting
901 $sum += $temp1 * $temp2;
904 my $rem = ( $sum % 11 );
905 $rem = 'X' if $rem == 10;
907 return "V$cardnumber$rem";
910 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
911 # better. I'll leave the original in in case it needs to be changed for you
912 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
913 my $sth = $dbh->prepare(
914 "select max(cast(cardnumber as signed)) from borrowers"
917 my ($result) = $sth->fetchrow;
920 return $cardnumber; # just here as a fallback/reminder
925 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
926 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
927 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
929 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
930 with children) and looks up the borrowers who are guaranteed by that
931 borrower (i.e., the patron's children).
933 C<&GetGuarantees> returns two values: an integer giving the number of
934 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
935 of references to hash, which gives the actual results.
941 my ($borrowernumber) = @_;
942 my $dbh = C4::Context->dbh;
945 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
947 $sth->execute($borrowernumber);
950 my $data = $sth->fetchall_arrayref({});
952 return ( scalar(@$data), $data );
955 =head2 UpdateGuarantees
957 &UpdateGuarantees($parent_borrno);
960 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
961 with the modified information
966 sub UpdateGuarantees {
968 my $dbh = C4::Context->dbh;
969 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
970 for ( my $i = 0 ; $i < $count ; $i++ ) {
973 # It looks like the $i is only being returned to handle walking through
974 # the array, which is probably better done as a foreach loop.
976 my $guaquery = qq|UPDATE borrowers
977 SET address='$data{'address'}',fax='$data{'fax'}',
978 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
979 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
981 my $sth3 = $dbh->prepare($guaquery);
986 =head2 GetPendingIssues
988 my $issues = &GetPendingIssues($borrowernumber);
990 Looks up what the patron with the given borrowernumber has borrowed.
992 C<&GetPendingIssues> returns a
993 reference-to-array where each element is a reference-to-hash; the
994 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
995 The keys include C<biblioitems> fields except marc and marcxml.
1000 sub GetPendingIssues {
1001 my ($borrowernumber) = @_;
1002 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1003 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1004 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1005 # FIXME: C4::Print::printslip tries to sort by timestamp!
1006 # FIXME: namespace collision: other collisions possible.
1007 # FIXME: most of this data isn't really being used by callers.
1008 my $sth = C4::Context->dbh->prepare(
1014 biblioitems.itemtype,
1017 biblioitems.publicationyear,
1018 biblioitems.publishercode,
1019 biblioitems.volumedate,
1020 biblioitems.volumedesc,
1023 issues.timestamp AS timestamp,
1024 issues.renewals AS renewals,
1025 items.renewals AS totalrenewals
1027 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1028 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1029 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1032 ORDER BY issues.issuedate"
1034 $sth->execute($borrowernumber);
1035 my $data = $sth->fetchall_arrayref({});
1036 my $today = C4::Dates->new->output('iso');
1038 $_->{date_due} or next;
1039 ($_->{date_due} lt $today) and $_->{overdue} = 1;
1046 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1048 Looks up what the patron with the given borrowernumber has borrowed,
1049 and sorts the results.
1051 C<$sortkey> is the name of a field on which to sort the results. This
1052 should be the name of a field in the C<issues>, C<biblio>,
1053 C<biblioitems>, or C<items> table in the Koha database.
1055 C<$limit> is the maximum number of results to return.
1057 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1058 reference-to-array, where each element is a reference-to-hash; the
1059 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1060 C<items> tables of the Koha database. C<$count> is the number of
1061 elements in C<$issues>
1067 my ( $borrowernumber, $order, $limit ) = @_;
1069 #FIXME: sanity-check order and limit
1070 my $dbh = C4::Context->dbh;
1073 "SELECT *,issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1075 LEFT JOIN items on items.itemnumber=issues.itemnumber
1076 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1077 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1078 WHERE borrowernumber=?
1080 SELECT *,old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1082 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1083 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1084 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1085 WHERE borrowernumber=?
1087 if ( $limit != 0 ) {
1088 $query .= " limit $limit";
1092 my $sth = $dbh->prepare($query);
1093 $sth->execute($borrowernumber, $borrowernumber);
1096 while ( my $data = $sth->fetchrow_hashref ) {
1097 $result[$i] = $data;
1102 # get all issued items for borrowernumber from oldissues table
1103 # large chunk of older issues data put into table oldissues
1104 # to speed up db calls for issuing items
1105 if ( C4::Context->preference("ReadingHistory") ) {
1106 # FIXME oldissues (not to be confused with old_issues) is
1107 # apparently specific to HLT. Not sure if the ReadingHistory
1108 # syspref is still required, as old_issues by design
1109 # is no longer checked with each loan.
1110 my $query2 = "SELECT * FROM oldissues
1111 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1112 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1113 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1114 WHERE borrowernumber=?
1116 if ( $limit != 0 ) {
1117 $limit = $limit - $count;
1118 $query2 .= " limit $limit";
1121 my $sth2 = $dbh->prepare($query2);
1122 $sth2->execute($borrowernumber);
1124 while ( my $data2 = $sth2->fetchrow_hashref ) {
1125 $result[$i] = $data2;
1132 return ( $i, \@result );
1136 =head2 GetMemberAccountRecords
1138 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1140 Looks up accounting data for the patron with the given borrowernumber.
1142 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1143 reference-to-array, where each element is a reference-to-hash; the
1144 keys are the fields of the C<accountlines> table in the Koha database.
1145 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1146 total amount outstanding for all of the account lines.
1151 sub GetMemberAccountRecords {
1152 my ($borrowernumber,$date) = @_;
1153 my $dbh = C4::Context->dbh;
1159 WHERE borrowernumber=?);
1160 my @bind = ($borrowernumber);
1161 if ($date && $date ne ''){
1162 $strsth.=" AND date < ? ";
1165 $strsth.=" ORDER BY date desc,timestamp DESC";
1166 my $sth= $dbh->prepare( $strsth );
1167 $sth->execute( @bind );
1169 while ( my $data = $sth->fetchrow_hashref ) {
1170 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1171 $data->{biblionumber} = $biblio->{biblionumber};
1172 $acctlines[$numlines] = $data;
1174 $total += int(100 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1178 return ( $total, \@acctlines,$numlines);
1181 =head2 GetBorNotifyAcctRecord
1183 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1185 Looks up accounting data for the patron with the given borrowernumber per file number.
1187 (FIXME - I'm not at all sure what this is about.)
1189 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1190 reference-to-array, where each element is a reference-to-hash; the
1191 keys are the fields of the C<accountlines> table in the Koha database.
1192 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1193 total amount outstanding for all of the account lines.
1197 sub GetBorNotifyAcctRecord {
1198 my ( $borrowernumber, $notifyid ) = @_;
1199 my $dbh = C4::Context->dbh;
1202 my $sth = $dbh->prepare(
1205 WHERE borrowernumber=?
1207 AND amountoutstanding != '0'
1208 ORDER BY notify_id,accounttype
1210 # AND (accounttype='FU' OR accounttype='N' OR accounttype='M'OR accounttype='A'OR accounttype='F'OR accounttype='L' OR accounttype='IP' OR accounttype='CH' OR accounttype='RE' OR accounttype='RL')
1212 $sth->execute( $borrowernumber, $notifyid );
1214 while ( my $data = $sth->fetchrow_hashref ) {
1215 $acctlines[$numlines] = $data;
1217 $total += int(100 * $data->{'amountoutstanding'});
1221 return ( $total, \@acctlines, $numlines );
1224 =head2 checkuniquemember (OUEST-PROVENCE)
1226 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1228 Checks that a member exists or not in the database.
1230 C<&result> is nonzero (=exist) or 0 (=does not exist)
1231 C<&categorycode> is from categorycode table
1232 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1233 C<&surname> is the surname
1234 C<&firstname> is the firstname (only if collectivity=0)
1235 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1239 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1240 # This is especially true since first name is not even a required field.
1242 sub checkuniquemember {
1243 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1244 my $dbh = C4::Context->dbh;
1245 my $request = ($collectivity) ?
1246 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1248 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1249 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1250 my $sth = $dbh->prepare($request);
1252 if ($collectivity) {
1253 $sth->execute( uc($surname) );
1254 } elsif($dateofbirth){
1255 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1257 $sth->execute( uc($surname), ucfirst($firstname));
1259 my @data = $sth->fetchrow;
1261 ( $data[0] ) and return $data[0], $data[1];
1265 sub checkcardnumber {
1266 my ($cardnumber,$borrowernumber) = @_;
1267 my $dbh = C4::Context->dbh;
1268 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1269 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1270 my $sth = $dbh->prepare($query);
1271 if ($borrowernumber) {
1272 $sth->execute($cardnumber,$borrowernumber);
1274 $sth->execute($cardnumber);
1276 if (my $data= $sth->fetchrow_hashref()){
1286 =head2 getzipnamecity (OUEST-PROVENCE)
1288 take all info from table city for the fields city and zip
1289 check for the name and the zip code of the city selected
1293 sub getzipnamecity {
1295 my $dbh = C4::Context->dbh;
1298 "select city_name,city_zipcode from cities where cityid=? ");
1299 $sth->execute($cityid);
1300 my @data = $sth->fetchrow;
1301 return $data[0], $data[1];
1305 =head2 getdcity (OUEST-PROVENCE)
1307 recover cityid with city_name condition
1312 my ($city_name) = @_;
1313 my $dbh = C4::Context->dbh;
1314 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1315 $sth->execute($city_name);
1316 my $data = $sth->fetchrow;
1321 =head2 GetExpiryDate
1323 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1325 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1326 Return date is also in ISO format.
1331 my ( $categorycode, $dateenrolled ) = @_;
1332 my $enrolmentperiod = 12; # reasonable default
1333 if ($categorycode) {
1334 my $dbh = C4::Context->dbh;
1335 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1336 $sth->execute($categorycode);
1337 $enrolmentperiod = $sth->fetchrow;
1339 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1340 my @date = split /-/,$dateenrolled;
1341 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1344 =head2 checkuserpassword (OUEST-PROVENCE)
1346 check for the password and login are not used
1347 return the number of record
1348 0=> NOT USED 1=> USED
1352 sub checkuserpassword {
1353 my ( $borrowernumber, $userid, $password ) = @_;
1354 $password = md5_base64($password);
1355 my $dbh = C4::Context->dbh;
1358 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1360 $sth->execute( $borrowernumber, $userid, $password );
1361 my $number_rows = $sth->fetchrow;
1362 return $number_rows;
1366 =head2 GetborCatFromCatType
1368 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1370 Looks up the different types of borrowers in the database. Returns two
1371 elements: a reference-to-array, which lists the borrower category
1372 codes, and a reference-to-hash, which maps the borrower category codes
1373 to category descriptions.
1378 sub GetborCatFromCatType {
1379 my ( $category_type, $action ) = @_;
1380 # FIXME - This API seems both limited and dangerous.
1381 my $dbh = C4::Context->dbh;
1382 my $request = qq| SELECT categorycode,description
1385 ORDER BY categorycode|;
1386 my $sth = $dbh->prepare($request);
1388 $sth->execute($category_type);
1397 while ( my $data = $sth->fetchrow_hashref ) {
1398 push @codes, $data->{'categorycode'};
1399 $labels{ $data->{'categorycode'} } = $data->{'description'};
1402 return ( \@codes, \%labels );
1405 =head2 GetBorrowercategory
1407 $hashref = &GetBorrowercategory($categorycode);
1409 Given the borrower's category code, the function returns the corresponding
1410 data hashref for a comprehensive information display.
1412 $arrayref_hashref = &GetBorrowercategory;
1413 If no category code provided, the function returns all the categories.
1417 sub GetBorrowercategory {
1419 my $dbh = C4::Context->dbh;
1423 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1425 WHERE categorycode = ?"
1427 $sth->execute($catcode);
1429 $sth->fetchrow_hashref;
1434 } # sub getborrowercategory
1436 =head2 GetBorrowercategoryList
1438 $arrayref_hashref = &GetBorrowercategoryList;
1439 If no category code provided, the function returns all the categories.
1443 sub GetBorrowercategoryList {
1444 my $dbh = C4::Context->dbh;
1449 ORDER BY description"
1453 $sth->fetchall_arrayref({});
1456 } # sub getborrowercategory
1458 =head2 ethnicitycategories
1460 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1462 Looks up the different ethnic types in the database. Returns two
1463 elements: a reference-to-array, which lists the ethnicity codes, and a
1464 reference-to-hash, which maps the ethnicity codes to ethnicity
1471 sub ethnicitycategories {
1472 my $dbh = C4::Context->dbh;
1473 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1477 while ( my $data = $sth->fetchrow_hashref ) {
1478 push @codes, $data->{'code'};
1479 $labels{ $data->{'code'} } = $data->{'name'};
1482 return ( \@codes, \%labels );
1487 $ethn_name = &fixEthnicity($ethn_code);
1489 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1490 corresponding descriptive name from the C<ethnicity> table in the
1491 Koha database ("European" or "Pacific Islander").
1498 my $ethnicity = shift;
1499 return unless $ethnicity;
1500 my $dbh = C4::Context->dbh;
1501 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1502 $sth->execute($ethnicity);
1503 my $data = $sth->fetchrow_hashref;
1505 return $data->{'name'};
1506 } # sub fixEthnicity
1510 $dateofbirth,$date = &GetAge($date);
1512 this function return the borrowers age with the value of dateofbirth
1518 my ( $date, $date_ref ) = @_;
1520 if ( not defined $date_ref ) {
1521 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1524 my ( $year1, $month1, $day1 ) = split /-/, $date;
1525 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1527 my $age = $year2 - $year1;
1528 if ( $month1 . $day1 > $month2 . $day2 ) {
1535 =head2 get_institutions
1536 $insitutions = get_institutions();
1538 Just returns a list of all the borrowers of type I, borrownumber and name
1543 sub get_institutions {
1544 my $dbh = C4::Context->dbh();
1547 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1551 while ( my $data = $sth->fetchrow_hashref() ) {
1552 $orgs{ $data->{'borrowernumber'} } = $data;
1557 } # sub get_institutions
1559 =head2 add_member_orgs
1561 add_member_orgs($borrowernumber,$borrowernumbers);
1563 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1568 sub add_member_orgs {
1569 my ( $borrowernumber, $otherborrowers ) = @_;
1570 my $dbh = C4::Context->dbh();
1572 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1573 my $sth = $dbh->prepare($query);
1574 foreach my $otherborrowernumber (@$otherborrowers) {
1575 $sth->execute( $borrowernumber, $otherborrowernumber );
1579 } # sub add_member_orgs
1581 =head2 GetCities (OUEST-PROVENCE)
1583 ($id_cityarrayref, $city_hashref) = &GetCities();
1585 Looks up the different city and zip in the database. Returns two
1586 elements: a reference-to-array, which lists the zip city
1587 codes, and a reference-to-hash, which maps the name of the city.
1588 WHERE =>OUEST PROVENCE OR EXTERIEUR
1594 #my ($type_city) = @_;
1595 my $dbh = C4::Context->dbh;
1596 my $query = qq|SELECT cityid,city_zipcode,city_name
1598 ORDER BY city_name|;
1599 my $sth = $dbh->prepare($query);
1601 #$sth->execute($type_city);
1605 # insert empty value to create a empty choice in cgi popup
1608 while ( my $data = $sth->fetchrow_hashref ) {
1609 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1610 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1613 #test to know if the table contain some records if no the function return nothing
1617 # all we have is the one blank row
1622 return ( \@id, \%city );
1626 =head2 GetSortDetails (OUEST-PROVENCE)
1628 ($lib) = &GetSortDetails($category,$sortvalue);
1630 Returns the authorized value details
1631 C<&$lib>return value of authorized value details
1632 C<&$sortvalue>this is the value of authorized value
1633 C<&$category>this is the value of authorized value category
1637 sub GetSortDetails {
1638 my ( $category, $sortvalue ) = @_;
1639 my $dbh = C4::Context->dbh;
1640 my $query = qq|SELECT lib
1641 FROM authorised_values
1643 AND authorised_value=? |;
1644 my $sth = $dbh->prepare($query);
1645 $sth->execute( $category, $sortvalue );
1646 my $lib = $sth->fetchrow;
1647 return ($lib) if ($lib);
1648 return ($sortvalue) unless ($lib);
1651 =head2 DeleteBorrower
1653 () = &DeleteBorrower($member);
1655 delete all data fo borrowers and add record to deletedborrowers table
1656 C<&$member>this is the borrowernumber
1660 sub MoveMemberToDeleted {
1662 my $dbh = C4::Context->dbh;
1664 $query = qq|SELECT *
1666 WHERE borrowernumber=?|;
1667 my $sth = $dbh->prepare($query);
1668 $sth->execute($member);
1669 my @data = $sth->fetchrow_array;
1672 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1673 . ( "?," x ( scalar(@data) - 1 ) )
1675 $sth->execute(@data);
1681 DelMember($borrowernumber);
1683 This function remove directly a borrower whitout writing it on deleteborrower.
1684 + Deletes reserves for the borrower
1689 my $dbh = C4::Context->dbh;
1690 my $borrowernumber = shift;
1691 #warn "in delmember with $borrowernumber";
1692 return unless $borrowernumber; # borrowernumber is mandatory.
1694 my $query = qq|DELETE
1696 WHERE borrowernumber=?|;
1697 my $sth = $dbh->prepare($query);
1698 $sth->execute($borrowernumber);
1703 WHERE borrowernumber = ?
1705 $sth = $dbh->prepare($query);
1706 $sth->execute($borrowernumber);
1708 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1712 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1714 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1716 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1721 sub ExtendMemberSubscriptionTo {
1722 my ( $borrowerid,$date) = @_;
1723 my $dbh = C4::Context->dbh;
1724 my $borrower = GetMember($borrowerid,'borrowernumber');
1726 $date=POSIX::strftime("%Y-%m-%d",localtime());
1727 my $borrower = GetMember($borrowerid,'borrowernumber');
1728 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1730 my $sth = $dbh->do(<<EOF);
1732 SET dateexpiry='$date'
1733 WHERE borrowernumber='$borrowerid'
1735 # add enrolmentfee if needed
1736 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1737 $sth->execute($borrower->{'categorycode'});
1738 my ($enrolmentfee) = $sth->fetchrow;
1739 if ($enrolmentfee && $enrolmentfee > 0) {
1740 # insert fee in patron debts
1741 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1743 return $date if ($sth);
1747 =head2 GetRoadTypes (OUEST-PROVENCE)
1749 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1751 Looks up the different road type . Returns two
1752 elements: a reference-to-array, which lists the id_roadtype
1753 codes, and a reference-to-hash, which maps the road type of the road .
1758 my $dbh = C4::Context->dbh;
1760 SELECT roadtypeid,road_type
1762 ORDER BY road_type|;
1763 my $sth = $dbh->prepare($query);
1768 # insert empty value to create a empty choice in cgi popup
1770 while ( my $data = $sth->fetchrow_hashref ) {
1772 push @id, $data->{'roadtypeid'};
1773 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1776 #test to know if the table contain some records if no the function return nothing
1784 return ( \@id, \%roadtype );
1790 =head2 GetTitles (OUEST-PROVENCE)
1792 ($borrowertitle)= &GetTitles();
1794 Looks up the different title . Returns array with all borrowers title
1799 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1800 unshift( @borrowerTitle, "" );
1801 my $count=@borrowerTitle;
1806 return ( \@borrowerTitle);
1810 =head2 GetPatronImage
1812 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1814 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1818 sub GetPatronImage {
1819 my ($cardnumber) = @_;
1820 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1821 my $dbh = C4::Context->dbh;
1822 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1823 my $sth = $dbh->prepare($query);
1824 $sth->execute($cardnumber);
1825 my $imagedata = $sth->fetchrow_hashref;
1826 my $dberror = $sth->errstr;
1827 warn "Database error!" if $sth->errstr;
1829 return $imagedata, $dberror;
1832 =head2 PutPatronImage
1834 PutPatronImage($cardnumber, $mimetype, $imgfile);
1836 Stores patron binary image data and mimetype in database.
1837 NOTE: This function is good for updating images as well as inserting new images in the database.
1841 sub PutPatronImage {
1842 my ($cardnumber, $mimetype, $imgfile) = @_;
1843 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1844 my $dbh = C4::Context->dbh;
1845 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1846 my $sth = $dbh->prepare($query);
1847 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1848 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1849 my $dberror = $sth->errstr;
1854 =head2 RmPatronImage
1856 my ($dberror) = RmPatronImage($cardnumber);
1858 Removes the image for the patron with the supplied cardnumber.
1863 my ($cardnumber) = @_;
1864 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1865 my $dbh = C4::Context->dbh;
1866 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1867 my $sth = $dbh->prepare($query);
1868 $sth->execute($cardnumber);
1869 my $dberror = $sth->errstr;
1870 warn "Database error!" if $sth->errstr;
1875 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1877 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1879 Returns the description of roadtype
1880 C<&$roadtype>return description of road type
1881 C<&$roadtypeid>this is the value of roadtype s
1885 sub GetRoadTypeDetails {
1886 my ($roadtypeid) = @_;
1887 my $dbh = C4::Context->dbh;
1891 WHERE roadtypeid=?|;
1892 my $sth = $dbh->prepare($query);
1893 $sth->execute($roadtypeid);
1894 my $roadtype = $sth->fetchrow;
1898 =head2 GetBorrowersWhoHaveNotBorrowedSince
1900 &GetBorrowersWhoHaveNotBorrowedSince($date)
1902 this function get all borrowers who haven't borrowed since the date given on input arg.
1906 sub GetBorrowersWhoHaveNotBorrowedSince {
1907 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.
1909 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1910 my $filterbranch = shift ||
1911 ((C4::Context->preference('IndependantBranches')
1912 && C4::Context->userenv
1913 && C4::Context->userenv->{flags}!=1
1914 && C4::Context->userenv->{branch})
1915 ? C4::Context->userenv->{branch}
1917 my $dbh = C4::Context->dbh;
1919 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1921 JOIN categories USING (categorycode)
1922 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1923 WHERE category_type <> 'S'
1926 if ($filterbranch && $filterbranch ne ""){
1927 $query.=" AND borrowers.branchcode= ?";
1928 push @query_params,$filterbranch;
1930 $query.=" GROUP BY borrowers.borrowernumber";
1932 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1933 push @query_params,$filterdate;
1935 warn $query if $debug;
1936 my $sth = $dbh->prepare($query);
1937 if (scalar(@query_params)>0){
1938 $sth->execute(@query_params);
1945 while ( my $data = $sth->fetchrow_hashref ) {
1946 push @results, $data;
1951 =head2 GetBorrowersWhoHaveNeverBorrowed
1953 $results = &GetBorrowersWhoHaveNeverBorrowed
1955 this function get all borrowers who have never borrowed.
1957 I<$result> is a ref to an array which all elements are a hasref.
1961 sub GetBorrowersWhoHaveNeverBorrowed {
1962 my $filterbranch = shift ||
1963 ((C4::Context->preference('IndependantBranches')
1964 && C4::Context->userenv
1965 && C4::Context->userenv->{flags}!=1
1966 && C4::Context->userenv->{branch})
1967 ? C4::Context->userenv->{branch}
1969 my $dbh = C4::Context->dbh;
1971 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1973 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1974 WHERE issues.borrowernumber IS NULL
1977 if ($filterbranch && $filterbranch ne ""){
1978 $query.=" AND borrowers.branchcode= ?";
1979 push @query_params,$filterbranch;
1981 warn $query if $debug;
1983 my $sth = $dbh->prepare($query);
1984 if (scalar(@query_params)>0){
1985 $sth->execute(@query_params);
1992 while ( my $data = $sth->fetchrow_hashref ) {
1993 push @results, $data;
1998 =head2 GetBorrowersWithIssuesHistoryOlderThan
2000 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2002 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2004 I<$result> is a ref to an array which all elements are a hashref.
2005 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2009 sub GetBorrowersWithIssuesHistoryOlderThan {
2010 my $dbh = C4::Context->dbh;
2011 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2012 my $filterbranch = shift ||
2013 ((C4::Context->preference('IndependantBranches')
2014 && C4::Context->userenv
2015 && C4::Context->userenv->{flags}!=1
2016 && C4::Context->userenv->{branch})
2017 ? C4::Context->userenv->{branch}
2020 SELECT count(borrowernumber) as n,borrowernumber
2022 WHERE returndate < ?
2023 AND borrowernumber IS NOT NULL
2026 push @query_params, $date;
2028 $query.=" AND branchcode = ?";
2029 push @query_params, $filterbranch;
2031 $query.=" GROUP BY borrowernumber ";
2032 warn $query if $debug;
2033 my $sth = $dbh->prepare($query);
2034 $sth->execute(@query_params);
2037 while ( my $data = $sth->fetchrow_hashref ) {
2038 push @results, $data;
2043 =head2 GetBorrowersNamesAndLatestIssue
2045 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2047 this function get borrowers Names and surnames and Issue information.
2049 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2050 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2054 sub GetBorrowersNamesAndLatestIssue {
2055 my $dbh = C4::Context->dbh;
2056 my @borrowernumbers=@_;
2058 SELECT surname,lastname, phone, email,max(timestamp)
2060 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2061 GROUP BY borrowernumber
2063 my $sth = $dbh->prepare($query);
2065 my $results = $sth->fetchall_arrayref({});
2073 my $success = DebarMember( $borrowernumber );
2075 marks a Member as debarred, and therefore unable to checkout any more
2079 true on success, false on failure
2086 my $borrowernumber = shift;
2088 return unless defined $borrowernumber;
2089 return unless $borrowernumber =~ /^\d+$/;
2091 return ModMember( borrowernumber => $borrowernumber,
2096 =head2 IsMemberBlocked
2100 my $blocked = IsMemberBlocked( $borrowernumber );
2102 return the status, and the number of day or documents, depends his punishment
2105 -1 if the user have overdue returns
2106 1 if the user is punished X days
2107 0 if the user is authorised to loan
2113 sub IsMemberBlocked {
2114 my $borrowernumber = shift;
2115 my $dbh = C4::Context->dbh;
2116 # if he have late issues
2117 my $sth = $dbh->prepare(
2118 "SELECT COUNT(*) as latedocs
2120 WHERE borrowernumber = ?
2121 AND date_due < now()"
2123 $sth->execute($borrowernumber);
2124 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
2127 return (-1, $latedocs) if $latedocs > 0;
2129 # or if he must wait to loan
2130 if(C4::Context->preference("item-level_itypes")){
2131 $sth = $dbh->prepare(
2133 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
2134 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
2136 LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
2137 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)
2138 WHERE finedays IS NOT NULL
2139 AND date_due < returndate
2140 AND borrowernumber = ?
2141 ORDER BY blockingdate DESC
2145 $sth = $dbh->prepare(
2147 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
2148 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
2150 LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
2151 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
2152 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype)
2153 WHERE finedays IS NOT NULL
2154 AND date_due < returndate
2155 AND borrowernumber = ?
2156 ORDER BY blockingdate DESC
2160 $sth->execute($borrowernumber);
2161 my $row = $sth->fetchrow_hashref;
2162 my $blockeddate = $row->{'blockeddate'};
2163 my $blockedcount = $row->{'blockedcount'};
2166 return (1, $blockedcount) if $blockedcount > 0;
2171 END { } # module clean-up code here (global destructor)