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
26 use Digest::MD5 qw(md5_base64);
27 use Date::Calc qw/Today Add_Delta_YM/;
28 use C4::Log; # logaction
32 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK);
34 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v ); };
38 C4::Members - Perl Module containing convenience functions for member handling
46 This module contains routines for adding, modifying and deleting members/patrons/borrowers
64 &GetMemberIssuesAndFines
79 &GetMemberAccountRecords
80 &GetBorNotifyAcctRecord
86 &GetBorrowersWhoHaveNotBorrowedSince
87 &GetBorrowersWhoHaveNeverBorrowed
88 &GetBorrowersWithIssuesHistoryOlderThan
109 &ExtendMemberSubscriptionTo
125 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
127 Looks up patrons (borrowers) by name.
129 BUGFIX 499: C<$type> is now used to determine type of search.
130 if $type is "simple", search is performed on the first letter of the
133 $category_type is used to get a specified type of user.
134 (mainly adults when creating a child.)
136 C<$searchstring> is a space-separated list of search terms. Each term
137 must match the beginning a borrower's surname, first name, or other
140 C<$filter> is assumed to be a list of elements to filter results on
142 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
144 C<&SearchMember> returns a two-element list. C<$borrowers> is a
145 reference-to-array; each element is a reference-to-hash, whose keys
146 are the fields of the C<borrowers> table in the Koha database.
147 C<$count> is the number of elements in C<$borrowers>.
152 #used by member enquiries from the intranet
155 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
156 my $dbh = C4::Context->dbh;
162 if ( $type eq "simple" ) # simple search for one letter only
167 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode ".
168 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
170 " WHERE (surname LIKE ? OR cardnumber like ?) ";
171 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
172 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
173 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
176 $query.=" ORDER BY $orderby";
177 @bind = ("$searchstring%","$searchstring");
179 else # advanced search looking in surname, firstname and othernames
181 @data = split( ' ', $searchstring );
183 $query = "SELECT * FROM borrowers
184 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
186 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
187 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
188 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
191 $query.="((surname LIKE ? OR surname LIKE ?
192 OR firstname LIKE ? OR firstname LIKE ?
193 OR othernames LIKE ? OR othernames LIKE ?)
195 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
197 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
198 "$data[0]%", "% $data[0]%"
200 for ( my $i = 1 ; $i < $count ; $i++ ) {
201 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
202 OR firstname LIKE ? OR firstname LIKE ?
203 OR othernames LIKE ? OR othernames LIKE ?)";
205 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
206 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
210 $query = $query . ") OR cardnumber LIKE ?
212 push( @bind, $searchstring );
217 my $sth = $dbh->prepare($query);
219 # warn "Q $orderby : $query";
220 $sth->execute(@bind);
222 my $data = $sth->fetchall_arrayref({});
225 return ( scalar(@$data), $data );
228 =head2 GetMemberDetails
230 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
232 Looks up a patron and returns information about him or her. If
233 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
234 up the borrower by number; otherwise, it looks up the borrower by card
237 C<$borrower> is a reference-to-hash whose keys are the fields of the
238 borrowers table in the Koha database. In addition,
239 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
240 about the patron. Its keys act as flags :
242 if $borrower->{flags}->{LOST} {
243 # Patron's card was reported lost
246 Each flag has a C<message> key, giving a human-readable explanation of
247 the flag. If the state of a flag means that the patron should not be
248 allowed to borrow any more books, then it will have a C<noissues> key
251 The possible flags are:
257 =item Shows the patron's credit or debt, if any.
265 =item (Gone, no address.) Set if the patron has left without giving a
274 =item Set if the patron's card has been reported as lost.
282 =item Set if the patron has been debarred.
290 =item Any additional notes about the patron.
298 =item Set if the patron has overdue items. This flag has several keys:
300 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
301 overdue items. Its elements are references-to-hash, each describing an
302 overdue item. The keys are selected fields from the issues, biblio,
303 biblioitems, and items tables of the Koha database.
305 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
306 the overdue items, one per line.
314 =item Set if any items that the patron has reserved are available.
316 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
317 available items. Each element is a reference-to-hash whose keys are
318 fields from the reserves table of the Koha database.
324 sub GetMemberDetails {
325 my ( $borrowernumber, $cardnumber ) = @_;
326 my $dbh = C4::Context->dbh;
329 if ($borrowernumber) {
330 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
331 $sth->execute($borrowernumber);
333 elsif ($cardnumber) {
334 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
335 $sth->execute($cardnumber);
340 my $borrower = $sth->fetchrow_hashref;
341 my ($amount) = GetMemberAccountRecords( $borrowernumber);
342 $borrower->{'amountoutstanding'} = $amount;
343 my $flags = patronflags( $borrower);
346 $sth = $dbh->prepare("select bit,flag from userflags");
348 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
349 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
350 $accessflagshash->{$flag} = 1;
354 $borrower->{'flags'} = $flags;
355 $borrower->{'authflags'} = $accessflagshash;
357 # find out how long the membership lasts
360 "select enrolmentperiod from categories where categorycode = ?");
361 $sth->execute( $borrower->{'categorycode'} );
362 my $enrolment = $sth->fetchrow;
363 $borrower->{'enrolmentperiod'} = $enrolment;
364 return ($borrower); #, $flags, $accessflagshash);
371 NOTE!: If you change this function, be sure to update the POD for
374 $flags = &patronflags($patron);
377 {message} Message showing patron's credit or debt
378 {noissues} Set if patron owes >$5.00
379 {GNA} Set if patron gone w/o address
380 {message} "Borrower has no valid address"
382 {LOST} Set if patron's card reported lost
383 {message} Message to this effect
385 {DBARRED} Set is patron is debarred
386 {message} Message to this effect
388 {NOTES} Set if patron has notes
389 {message} Notes about patron
390 {ODUES} Set if patron has overdue books
392 {itemlist} ref-to-array: list of overdue books
393 {itemlisttext} Text list of overdue items
394 {WAITING} Set if there are items available that the
396 {message} Message to this effect
397 {itemlist} ref-to-array: list of available items
403 my ( $patroninformation) = @_;
404 my $dbh=C4::Context->dbh;
405 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
408 my $noissuescharge = C4::Context->preference("noissuescharge");
409 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
410 if ( $amount > $noissuescharge ) {
411 $flaginfo{'noissues'} = 1;
413 $flags{'CHARGES'} = \%flaginfo;
415 elsif ( $amount < 0 ) {
417 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
418 $flags{'CHARGES'} = \%flaginfo;
420 if ( $patroninformation->{'gonenoaddress'}
421 && $patroninformation->{'gonenoaddress'} == 1 )
424 $flaginfo{'message'} = 'Borrower has no valid address.';
425 $flaginfo{'noissues'} = 1;
426 $flags{'GNA'} = \%flaginfo;
428 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
430 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
431 $flaginfo{'noissues'} = 1;
432 $flags{'LOST'} = \%flaginfo;
434 if ( $patroninformation->{'debarred'}
435 && $patroninformation->{'debarred'} == 1 )
438 $flaginfo{'message'} = 'Borrower is Debarred.';
439 $flaginfo{'noissues'} = 1;
440 $flags{'DBARRED'} = \%flaginfo;
442 if ( $patroninformation->{'borrowernotes'}
443 && $patroninformation->{'borrowernotes'} )
446 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
447 $flags{'NOTES'} = \%flaginfo;
449 my ( $odues, $itemsoverdue ) =
450 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
453 $flaginfo{'message'} = "Yes";
454 $flaginfo{'itemlist'} = $itemsoverdue;
455 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
458 $flaginfo{'itemlisttext'} .=
459 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
461 $flags{'ODUES'} = \%flaginfo;
463 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
464 my $nowaiting = scalar @itemswaiting;
465 if ( $nowaiting > 0 ) {
467 $flaginfo{'message'} = "Reserved items available";
468 $flaginfo{'itemlist'} = \@itemswaiting;
469 $flags{'WAITING'} = \%flaginfo;
477 $borrower = &GetMember($information, $type);
479 Looks up information about a patron (borrower) by either card number
480 ,firstname, or borrower number, depending on $type value.
481 If C<$type> == 'cardnumber', C<&GetBorrower>
482 searches by cardnumber then by firstname if not found in cardnumber;
483 otherwise, it searches by borrowernumber.
485 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
486 the C<borrowers> table in the Koha database.
492 my ( $information, $type ) = @_;
493 my $dbh = C4::Context->dbh;
495 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
496 $information = uc $information;
499 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where $type=?"
501 $sth->execute($information);
506 "Select borrowers.*,categories.category_type, categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
508 $sth->execute($information);
510 my $data = $sth->fetchrow_hashref;
516 elsif ($type eq 'cardnumber' ||$type eq 'firstname') { # try with firstname
519 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where firstname like ?"
521 $sth->execute($information);
522 my $data = $sth->fetchrow_hashref;
531 =item GetMemberIssuesAndFines
533 ($borrowed, $due, $fine) = &GetMemberIssuesAndFines($borrowernumber);
535 Returns aggregate data about items borrowed by the patron with the
536 given borrowernumber.
538 C<&GetMemberIssuesAndFines> returns a three-element array. C<$borrowed> is the
539 number of books the patron currently has borrowed. C<$due> is the
540 number of overdue items the patron currently has borrowed. C<$fine> is
541 the total fine currently due by the borrower.
546 sub GetMemberIssuesAndFines {
547 my ( $borrowernumber ) = @_;
548 my $dbh = C4::Context->dbh;
550 "Select count(*) from issues where borrowernumber='$borrowernumber' and
554 my $sth = $dbh->prepare($query);
556 my $data = $sth->fetchrow_hashref;
558 $sth = $dbh->prepare(
559 "Select count(*) from issues where
560 borrowernumber='$borrowernumber' and date_due < now() and returndate is NULL"
563 my $data2 = $sth->fetchrow_hashref;
565 $sth = $dbh->prepare(
566 "Select sum(amountoutstanding) from accountlines where
567 borrowernumber='$borrowernumber'"
570 my $data3 = $sth->fetchrow_hashref;
573 return ( $data2->{'count(*)'}, $data->{'count(*)'},
574 $data3->{'sum(amountoutstanding)'} );
581 &ModMember($borrowernumber);
583 Modify borrower's data
590 my $dbh = C4::Context->dbh;
591 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} ) if ($data{'dateofbirth'} );
592 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} ) if ($data{'dateexpiry'} );
593 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
594 # warn Data::Dumper::Dumper(%data);
595 # warn "num user".$data{'borrowernumber'};
596 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
598 my %hashborrowerfields;
599 while (my ($field)=$qborrower->fetchrow){
600 $hashborrowerfields{$field}=1;
604 $data{'userid'} = '' if ( $data{'password'} eq '' );
607 # test to know if u must update or not the borrower password
608 if ( $data{'password'} eq '****' ) {
609 delete $data{'password'};
611 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_}) } ;
612 $query = "UPDATE borrowers SET ".join (",",@parameters)
613 ." WHERE borrowernumber=$data{'borrowernumber'}";
615 $sth = $dbh->prepare($query);
619 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne '' );
620 delete $data{'password'} if ($data{password} eq "");
622 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_})} ;
624 $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
626 $sth = $dbh->prepare($query);
631 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
632 # so when we update information for an adult we should check for guarantees and update the relevant part
633 # of their records, ie addresses and phone numbers
634 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
635 if ( $borrowercategory->{'category_type'} eq 'A' ) {
636 # is adult check guarantees;
637 UpdateGuarantees(%data);
640 &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"")
641 if C4::Context->preference("BorrowersLog");
649 $borrowernumber = &AddMember(%borrower);
651 insert new borrower into table
652 Returns the borrowernumber
659 my $dbh = C4::Context->dbh;
660 $data{'userid'} = '' unless $data{'password'};
661 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
662 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
663 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
664 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
666 "insert into borrowers set cardnumber="
667 . $dbh->quote( $data{'cardnumber'} )
669 . $dbh->quote( $data{'surname'} )
671 . $dbh->quote( $data{'firstname'} )
673 . $dbh->quote( $data{'title'} )
675 . $dbh->quote( $data{'othernames'} )
677 . $dbh->quote( $data{'initials'} )
679 . $dbh->quote( $data{'streetnumber'} )
681 . $dbh->quote( $data{'streettype'} )
683 . $dbh->quote( $data{'address'} )
685 . $dbh->quote( $data{'address2'} )
687 . $dbh->quote( $data{'zipcode'} )
689 . $dbh->quote( $data{'city'} )
691 . $dbh->quote( $data{'phone'} )
693 . $dbh->quote( $data{'email'} )
695 . $dbh->quote( $data{'mobile'} )
697 . $dbh->quote( $data{'phonepro'} )
699 . $dbh->quote( $data{'opacnote'} )
701 . $dbh->quote( $data{'guarantorid'} )
703 . $dbh->quote( $data{'dateofbirth'} )
705 . $dbh->quote( $data{'branchcode'} )
707 . $dbh->quote( $data{'categorycode'} )
709 . $dbh->quote( $data{'dateenrolled'} )
711 . $dbh->quote( $data{'contactname'} )
713 . $dbh->quote( $data{'borrowernotes'} )
715 . $dbh->quote( $data{'dateexpiry'} )
717 . $dbh->quote( $data{'contactnote'} )
719 . $dbh->quote( $data{'B_address'} )
721 . $dbh->quote( $data{'B_zipcode'} )
723 . $dbh->quote( $data{'B_city'} )
725 . $dbh->quote( $data{'B_phone'} )
727 . $dbh->quote( $data{'B_email'}, )
729 . $dbh->quote( $data{'password'} )
731 . $dbh->quote( $data{'userid'} )
733 . $dbh->quote( $data{'sort1'} )
735 . $dbh->quote( $data{'sort2'} )
737 . $dbh->quote( $data{'contacttitle'} )
739 . $dbh->quote( $data{'emailpro'} )
740 . ",contactfirstname="
741 . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
742 . $dbh->quote( $data{'sex'} ) . ",fax="
743 . $dbh->quote( $data{'fax'} )
745 . $dbh->quote( $data{'relationship'} )
747 . $dbh->quote( $data{'B_streetnumber'} )
749 . $dbh->quote( $data{'B_streettype'} )
751 . $dbh->quote( $data{'gonenoaddress'} )
753 . $dbh->quote( $data{'lost'} )
755 . $dbh->quote( $data{'debarred'} )
757 . $dbh->quote( $data{'ethnicity'} )
759 . $dbh->quote( $data{'ethnotes'} );
761 my $sth = $dbh->prepare($query);
764 $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
766 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"")
767 if C4::Context->preference("BorrowersLog");
769 return $data{'borrowernumber'};
773 my ($uid,$member) = @_;
774 my $dbh = C4::Context->dbh;
775 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
776 # Then we need to tell the user and have them create a new one.
779 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
780 $sth->execute( $uid, $member );
781 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
791 my ( $uid, $member, $digest ) = @_;
792 my $dbh = C4::Context->dbh;
794 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
795 #Then we need to tell the user and have them create a new one.
798 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
799 $sth->execute( $uid, $member );
800 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
804 #Everything is good so we can update the information.
807 "update borrowers set userid=?, password=? where borrowernumber=?");
808 $sth->execute( $uid, $digest, $member );
812 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"")
813 if C4::Context->preference("BorrowersLog");
818 =item fixup_cardnumber
820 Warning: The caller is responsible for locking the members table in write
821 mode, to avoid database corruption.
825 use vars qw( @weightings );
826 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
828 sub fixup_cardnumber ($) {
829 my ($cardnumber) = @_;
830 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
831 $autonumber_members = 0 unless defined $autonumber_members;
833 # Find out whether member numbers should be generated
834 # automatically. Should be either "1" or something else.
835 # Defaults to "0", which is interpreted as "no".
837 # if ($cardnumber !~ /\S/ && $autonumber_members) {
838 if ($autonumber_members) {
839 my $dbh = C4::Context->dbh;
840 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
842 # if checkdigit is selected, calculate katipo-style cardnumber.
843 # otherwise, just use the max()
844 # purpose: generate checksum'd member numbers.
845 # We'll assume we just got the max value of digits 2-8 of member #'s
846 # from the database and our job is to increment that by one,
847 # determine the 1st and 9th digits and return the full string.
850 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
854 my $data = $sth->fetchrow_hashref;
855 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
857 if ( !$cardnumber ) { # If DB has no values,
858 $cardnumber = 1000000; # start at 1000000
865 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
867 # read weightings, left to right, 1 char at a time
868 my $temp1 = $weightings[$i];
870 # sequence left to right, 1 char at a time
871 my $temp2 = substr( $cardnumber, $i, 1 );
873 # mult each char 1-7 by its corresponding weighting
874 $sum += $temp1 * $temp2;
877 my $rem = ( $sum % 11 );
878 $rem = 'X' if $rem == 10;
880 $cardnumber = "V$cardnumber$rem";
884 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
885 # better. I'll leave the original in in case it needs to be changed for you
888 "select max(cast(cardnumber as signed)) from borrowers");
890 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
894 my ($result) = $sth->fetchrow;
896 $cardnumber = $result + 1;
904 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
905 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
906 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
908 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
909 with children) and looks up the borrowers who are guaranteed by that
910 borrower (i.e., the patron's children).
912 C<&GetGuarantees> returns two values: an integer giving the number of
913 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
914 of references to hash, which gives the actual results.
920 my ($borrowernumber) = @_;
921 my $dbh = C4::Context->dbh;
924 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
926 $sth->execute($borrowernumber);
929 my $data = $sth->fetchall_arrayref({});
931 return ( scalar(@$data), $data );
934 =head2 UpdateGuarantees
936 &UpdateGuarantees($parent_borrno);
939 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
940 with the modified information
945 sub UpdateGuarantees {
947 my $dbh = C4::Context->dbh;
948 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
949 for ( my $i = 0 ; $i < $count ; $i++ ) {
952 # It looks like the $i is only being returned to handle walking through
953 # the array, which is probably better done as a foreach loop.
955 my $guaquery = qq|UPDATE borrowers
956 SET address='$data{'address'}',fax='$data{'fax'}',
957 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
958 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
960 my $sth3 = $dbh->prepare($guaquery);
965 =head2 GetPendingIssues
967 ($count, $issues) = &GetPendingIssues($borrowernumber);
969 Looks up what the patron with the given borrowernumber has borrowed.
971 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
972 reference-to-array, where each element is a reference-to-hash; the
973 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
974 in the Koha database. C<$count> is the number of elements in
980 sub GetPendingIssues {
981 my ($borrowernumber) = @_;
982 my $dbh = C4::Context->dbh;
984 my $sth = $dbh->prepare(
985 "SELECT * FROM issues
986 LEFT JOIN items ON issues.itemnumber=items.itemnumber
987 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
988 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
991 AND returndate IS NULL
992 ORDER BY issues.issuedate"
994 $sth->execute($borrowernumber);
995 my $data = $sth->fetchall_arrayref({});
996 my $today = POSIX::strftime("%Y%m%d", localtime);
998 my $datedue = $_->{'date_due'};
1000 if ( $datedue < $today ) {
1001 $_->{'overdue'} = 1;
1005 return ( scalar(@$data), $data );
1010 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1012 Looks up what the patron with the given borrowernumber has borrowed,
1013 and sorts the results.
1015 C<$sortkey> is the name of a field on which to sort the results. This
1016 should be the name of a field in the C<issues>, C<biblio>,
1017 C<biblioitems>, or C<items> table in the Koha database.
1019 C<$limit> is the maximum number of results to return.
1021 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1022 reference-to-array, where each element is a reference-to-hash; the
1023 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1024 C<items> tables of the Koha database. C<$count> is the number of
1025 elements in C<$issues>
1031 my ( $borrowernumber, $order, $limit ) = @_;
1033 #FIXME: sanity-check order and limit
1034 my $dbh = C4::Context->dbh;
1037 "Select *,items.timestamp AS itemstimestamp from
1039 LEFT JOIN items on items.itemnumber=issues.itemnumber
1040 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1041 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1042 where borrowernumber=?
1044 if ( $limit != 0 ) {
1045 $query .= " limit $limit";
1049 my $sth = $dbh->prepare($query);
1050 $sth->execute($borrowernumber);
1053 while ( my $data = $sth->fetchrow_hashref ) {
1054 $result[$i] = $data;
1059 # get all issued items for borrowernumber from oldissues table
1060 # large chunk of older issues data put into table oldissues
1061 # to speed up db calls for issuing items
1062 if ( C4::Context->preference("ReadingHistory") ) {
1063 my $query2 = "SELECT * FROM oldissues
1064 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1065 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1066 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1067 WHERE borrowernumber=?
1069 if ( $limit != 0 ) {
1070 $limit = $limit - $count;
1071 $query2 .= " limit $limit";
1074 my $sth2 = $dbh->prepare($query2);
1075 $sth2->execute($borrowernumber);
1077 while ( my $data2 = $sth2->fetchrow_hashref ) {
1078 $result[$i] = $data2;
1085 return ( $i, \@result );
1089 =head2 GetMemberAccountRecords
1091 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1093 Looks up accounting data for the patron with the given borrowernumber.
1095 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1096 reference-to-array, where each element is a reference-to-hash; the
1097 keys are the fields of the C<accountlines> table in the Koha database.
1098 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1099 total amount outstanding for all of the account lines.
1104 sub GetMemberAccountRecords {
1105 my ($borrowernumber,$date) = @_;
1106 my $dbh = C4::Context->dbh;
1112 WHERE borrowernumber=?);
1113 my @bind = ($borrowernumber);
1114 if ($date && $date ne ''){
1120 ORDER BY date desc,timestamp DESC";
1121 my $sth= $dbh->prepare( $strsth );
1122 $sth->execute( @bind );
1124 while ( my $data = $sth->fetchrow_hashref ) {
1125 $acctlines[$numlines] = $data;
1127 $total += $data->{'amountoutstanding'};
1130 return ( $total, \@acctlines,$numlines);
1133 =head2 GetBorNotifyAcctRecord
1135 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1137 Looks up accounting data for the patron with the given borrowernumber per file number.
1139 (FIXME - I'm not at all sure what this is about.)
1141 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1142 reference-to-array, where each element is a reference-to-hash; the
1143 keys are the fields of the C<accountlines> table in the Koha database.
1144 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1145 total amount outstanding for all of the account lines.
1149 sub GetBorNotifyAcctRecord {
1150 my ( $borrowernumber, $notifyid ) = @_;
1151 my $dbh = C4::Context->dbh;
1154 my $query = qq| SELECT *
1156 WHERE borrowernumber=?
1158 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')
1159 AND amountoutstanding != '0'
1160 ORDER BY notify_id,accounttype
1162 my $sth = $dbh->prepare($query);
1164 $sth->execute( $borrowernumber, $notifyid );
1166 while ( my $data = $sth->fetchrow_hashref ) {
1167 $acctlines[$numlines] = $data;
1169 $total += $data->{'amountoutstanding'};
1172 return ( $total, \@acctlines, $numlines );
1175 =head2 checkuniquemember (OUEST-PROVENCE)
1177 $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1179 Checks that a member exists or not in the database.
1181 C<&result> is 1 (=exist) or 0 (=does not exist)
1182 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1183 C<&surname> is the surname
1184 C<&categorycode> is from categorycode table
1185 C<&firstname> is the firstname (only if collectivity=0)
1186 C<&dateofbirth> is the date of birth (only if collectivity=0)
1190 sub checkuniquemember {
1191 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1192 my $dbh = C4::Context->dbh;
1194 if ($collectivity) {
1196 # $request="select count(*) from borrowers where surname=? and categorycode=?";
1198 "select borrowernumber,categorycode from borrowers where surname=? ";
1202 # $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1204 "select borrowernumber,categorycode from borrowers where surname=? and firstname=? and dateofbirth=?";
1206 my $sth = $dbh->prepare($request);
1207 if ($collectivity) {
1208 $sth->execute( uc($surname) );
1211 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1213 my @data = $sth->fetchrow;
1216 return $data[0], $data[1];
1226 sub checkcardnumber {
1227 my ($cardnumber) = @_;
1228 my $dbh = C4::Context->dbh;
1229 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1230 my $sth = $dbh->prepare($query);
1231 $sth->execute($cardnumber);
1232 if (my $data= $sth->fetchrow_hashref()){
1242 =head2 getzipnamecity (OUEST-PROVENCE)
1244 take all info from table city for the fields city and zip
1245 check for the name and the zip code of the city selected
1249 sub getzipnamecity {
1251 my $dbh = C4::Context->dbh;
1254 "select city_name,city_zipcode from cities where cityid=? ");
1255 $sth->execute($cityid);
1256 my @data = $sth->fetchrow;
1257 return $data[0], $data[1];
1261 =head2 getdcity (OUEST-PROVENCE)
1263 recover cityid with city_name condition
1268 my ($city_name) = @_;
1269 my $dbh = C4::Context->dbh;
1270 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1271 $sth->execute($city_name);
1272 my $data = $sth->fetchrow;
1277 =head2 GetExpiryDate
1279 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1280 process expiry date given a date and a categorycode
1284 my ( $categorycode, $dateenrolled ) = @_;
1285 my $dbh = C4::Context->dbh;
1288 "select enrolmentperiod from categories where categorycode=?");
1289 $sth->execute($categorycode);
1290 my ($enrolmentperiod) = $sth->fetchrow;
1291 $enrolmentperiod = 12 unless ($enrolmentperiod);
1292 my @date=split /-/,format_date_in_iso($dateenrolled);
1293 @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1294 return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1297 =head2 checkuserpassword (OUEST-PROVENCE)
1299 check for the password and login are not used
1300 return the number of record
1301 0=> NOT USED 1=> USED
1305 sub checkuserpassword {
1306 my ( $borrowernumber, $userid, $password ) = @_;
1307 $password = md5_base64($password);
1308 my $dbh = C4::Context->dbh;
1311 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1313 $sth->execute( $borrowernumber, $userid, $password );
1314 my $number_rows = $sth->fetchrow;
1315 return $number_rows;
1319 =head2 GetborCatFromCatType
1321 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1323 Looks up the different types of borrowers in the database. Returns two
1324 elements: a reference-to-array, which lists the borrower category
1325 codes, and a reference-to-hash, which maps the borrower category codes
1326 to category descriptions.
1331 sub GetborCatFromCatType {
1332 my ( $category_type, $action ) = @_;
1333 my $dbh = C4::Context->dbh;
1334 my $request = qq| SELECT categorycode,description
1337 ORDER BY categorycode|;
1338 my $sth = $dbh->prepare($request);
1340 $sth->execute($category_type);
1349 while ( my $data = $sth->fetchrow_hashref ) {
1350 push @codes, $data->{'categorycode'};
1351 $labels{ $data->{'categorycode'} } = $data->{'description'};
1354 return ( \@codes, \%labels );
1357 =head2 GetBorrowercategory
1359 $hashref = &GetBorrowercategory($categorycode);
1361 Given the borrower's category code, the function returns the corresponding
1362 data hashref for a comprehensive information display.
1366 sub GetBorrowercategory {
1368 my $dbh = C4::Context->dbh;
1371 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1373 WHERE categorycode = ?"
1375 $sth->execute($catcode);
1377 $sth->fetchrow_hashref;
1380 } # sub getborrowercategory
1382 =head2 ethnicitycategories
1384 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1386 Looks up the different ethnic types in the database. Returns two
1387 elements: a reference-to-array, which lists the ethnicity codes, and a
1388 reference-to-hash, which maps the ethnicity codes to ethnicity
1395 sub ethnicitycategories {
1396 my $dbh = C4::Context->dbh;
1397 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1401 while ( my $data = $sth->fetchrow_hashref ) {
1402 push @codes, $data->{'code'};
1403 $labels{ $data->{'code'} } = $data->{'name'};
1406 return ( \@codes, \%labels );
1411 $ethn_name = &fixEthnicity($ethn_code);
1413 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1414 corresponding descriptive name from the C<ethnicity> table in the
1415 Koha database ("European" or "Pacific Islander").
1422 my $ethnicity = shift;
1423 return unless $ethnicity;
1424 my $dbh = C4::Context->dbh;
1425 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1426 $sth->execute($ethnicity);
1427 my $data = $sth->fetchrow_hashref;
1429 return $data->{'name'};
1430 } # sub fixEthnicity
1434 $dateofbirth,$date = &GetAge($date);
1436 this function return the borrowers age with the value of dateofbirth
1442 my ( $date, $date_ref ) = @_;
1444 if ( not defined $date_ref ) {
1445 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1448 my ( $year1, $month1, $day1 ) = split /-/, $date;
1449 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1451 my $age = $year2 - $year1;
1452 if ( $month1 . $day1 > $month2 . $day2 ) {
1459 =head2 get_institutions
1460 $insitutions = get_institutions();
1462 Just returns a list of all the borrowers of type I, borrownumber and name
1467 sub get_institutions {
1468 my $dbh = C4::Context->dbh();
1471 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1475 while ( my $data = $sth->fetchrow_hashref() ) {
1476 $orgs{ $data->{'borrowernumber'} } = $data;
1481 } # sub get_institutions
1483 =head2 add_member_orgs
1485 add_member_orgs($borrowernumber,$borrowernumbers);
1487 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1492 sub add_member_orgs {
1493 my ( $borrowernumber, $otherborrowers ) = @_;
1494 my $dbh = C4::Context->dbh();
1496 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1497 my $sth = $dbh->prepare($query);
1498 foreach my $otherborrowernumber (@$otherborrowers) {
1499 $sth->execute( $borrowernumber, $otherborrowernumber );
1503 } # sub add_member_orgs
1505 =head2 GetCities (OUEST-PROVENCE)
1507 ($id_cityarrayref, $city_hashref) = &GetCities();
1509 Looks up the different city and zip in the database. Returns two
1510 elements: a reference-to-array, which lists the zip city
1511 codes, and a reference-to-hash, which maps the name of the city.
1512 WHERE =>OUEST PROVENCE OR EXTERIEUR
1518 #my ($type_city) = @_;
1519 my $dbh = C4::Context->dbh;
1520 my $query = qq|SELECT cityid,city_name
1522 ORDER BY city_name|;
1523 my $sth = $dbh->prepare($query);
1525 #$sth->execute($type_city);
1530 # insert empty value to create a empty choice in cgi popup
1532 while ( my $data = $sth->fetchrow_hashref ) {
1534 push @id, $data->{'cityid'};
1535 $city{ $data->{'cityid'} } = $data->{'city_name'};
1538 #test to know if the table contain some records if no the function return nothing
1546 return ( \@id, \%city );
1550 =head2 GetSortDetails (OUEST-PROVENCE)
1552 ($lib) = &GetSortDetails($category,$sortvalue);
1554 Returns the authorized value details
1555 C<&$lib>return value of authorized value details
1556 C<&$sortvalue>this is the value of authorized value
1557 C<&$category>this is the value of authorized value category
1561 sub GetSortDetails {
1562 my ( $category, $sortvalue ) = @_;
1563 my $dbh = C4::Context->dbh;
1564 my $query = qq|SELECT lib
1565 FROM authorised_values
1567 AND authorised_value=? |;
1568 my $sth = $dbh->prepare($query);
1569 $sth->execute( $category, $sortvalue );
1570 my $lib = $sth->fetchrow;
1574 =head2 DeleteBorrower
1576 () = &DeleteBorrower($member);
1578 delete all data fo borrowers and add record to deletedborrowers table
1579 C<&$member>this is the borrowernumber
1583 sub MoveMemberToDeleted {
1585 my $dbh = C4::Context->dbh;
1587 $query = qq|SELECT *
1589 WHERE borrowernumber=?|;
1590 my $sth = $dbh->prepare($query);
1591 $sth->execute($member);
1592 my @data = $sth->fetchrow_array;
1595 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1596 . ( "?," x ( scalar(@data) - 1 ) )
1598 $sth->execute(@data);
1604 DelMember($borrowernumber);
1606 This function remove directly a borrower whitout writing it on deleteborrower.
1607 + Deletes reserves for the borrower
1612 my $dbh = C4::Context->dbh;
1613 my $borrowernumber = shift;
1614 warn "in delmember with $borrowernumber";
1615 return unless $borrowernumber; # borrowernumber is mandatory.
1617 my $query = qq|DELETE
1619 WHERE borrowernumber=?|;
1620 my $sth = $dbh->prepare($query);
1621 $sth->execute($borrowernumber);
1626 WHERE borrowernumber = ?
1628 $sth = $dbh->prepare($query);
1629 $sth->execute($borrowernumber);
1631 &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"")
1632 if C4::Context->preference("BorrowersLog");
1636 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1638 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1639 Extending the subscription to a given date or to the expiry date calculated on local date.
1643 sub ExtendMemberSubscriptionTo {
1644 my ( $borrowerid,$date) = @_;
1645 my $dbh = C4::Context->dbh;
1647 $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1648 my $borrower = GetMember($borrowerid,'borrowernumber');
1649 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1651 my $sth = $dbh->do(<<EOF);
1653 SET dateexpiry='$date'
1654 WHERE borrowernumber='$borrowerid'
1656 return $date if ($sth);
1660 =head2 GetRoadTypes (OUEST-PROVENCE)
1662 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1664 Looks up the different road type . Returns two
1665 elements: a reference-to-array, which lists the id_roadtype
1666 codes, and a reference-to-hash, which maps the road type of the road .
1672 my $dbh = C4::Context->dbh;
1674 SELECT roadtypeid,road_type
1676 ORDER BY road_type|;
1677 my $sth = $dbh->prepare($query);
1682 # insert empty value to create a empty choice in cgi popup
1684 while ( my $data = $sth->fetchrow_hashref ) {
1686 push @id, $data->{'roadtypeid'};
1687 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1690 #test to know if the table contain some records if no the function return nothing
1698 return ( \@id, \%roadtype );
1704 =head2 GetTitles (OUEST-PROVENCE)
1706 ($borrowertitle)= &GetTitles();
1708 Looks up the different title . Returns array with all borrowers title
1713 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1714 unshift( @borrowerTitle, "" );
1715 return ( \@borrowerTitle);
1720 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1722 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1724 Returns the description of roadtype
1725 C<&$roadtype>return description of road type
1726 C<&$roadtypeid>this is the value of roadtype s
1730 sub GetRoadTypeDetails {
1731 my ($roadtypeid) = @_;
1732 my $dbh = C4::Context->dbh;
1736 WHERE roadtypeid=?|;
1737 my $sth = $dbh->prepare($query);
1738 $sth->execute($roadtypeid);
1739 my $roadtype = $sth->fetchrow;
1743 =head2 GetBorrowersWhoHaveNotBorrowedSince
1745 &GetBorrowersWhoHaveNotBorrowedSince($date)
1747 this function get all borrowers who haven't borrowed since the date given on input arg.
1751 sub GetBorrowersWhoHaveNotBorrowedSince {
1753 return unless $date; # date is mandatory.
1754 my $dbh = C4::Context->dbh;
1756 SELECT borrowers.borrowernumber,max(timestamp)
1758 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1759 WHERE issues.borrowernumber IS NOT NULL
1760 GROUP BY borrowers.borrowernumber
1762 my $sth = $dbh->prepare($query);
1766 while ( my $data = $sth->fetchrow_hashref ) {
1767 push @results, $data;
1772 =head2 GetBorrowersWhoHaveNeverBorrowed
1774 $results = &GetBorrowersWhoHaveNeverBorrowed
1776 this function get all borrowers who have never borrowed.
1778 I<$result> is a ref to an array which all elements are a hasref.
1782 sub GetBorrowersWhoHaveNeverBorrowed {
1783 my $dbh = C4::Context->dbh;
1785 SELECT borrowers.borrowernumber,max(timestamp)
1787 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1788 WHERE issues.borrowernumber IS NULL
1790 my $sth = $dbh->prepare($query);
1793 while ( my $data = $sth->fetchrow_hashref ) {
1794 push @results, $data;
1799 =head2 GetBorrowersWithIssuesHistoryOlderThan
1801 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1803 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1805 I<$result> is a ref to an array which all elements are a hashref.
1806 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1810 sub GetBorrowersWithIssuesHistoryOlderThan {
1811 my $dbh = C4::Context->dbh;
1813 return unless $date; # date is mandatory.
1815 SELECT count(borrowernumber) as n,borrowernumber
1817 WHERE returndate < ?
1818 AND borrowernumber IS NOT NULL
1819 GROUP BY borrowernumber
1821 my $sth = $dbh->prepare($query);
1822 $sth->execute($date);
1825 while ( my $data = $sth->fetchrow_hashref ) {
1826 push @results, $data;
1831 END { } # module clean-up code here (global destructor)