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);
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<&SearchMember> returns a two-element list. C<$borrowers> is a
141 reference-to-array; each element is a reference-to-hash, whose keys
142 are the fields of the C<borrowers> table in the Koha database.
143 C<$count> is the number of elements in C<$borrowers>.
148 #used by member enquiries from the intranet
151 my ($searchstring, $orderby, $type,$category_type ) = @_;
152 my $dbh = C4::Context->dbh;
158 if ( $type eq "simple" ) # simple search for one letter only
161 "SELECT * FROM borrowers
162 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode ".
163 ($category_type?" AND category_type = ".$dbh->quote($category_type):"").
164 " WHERE surname LIKE ? OR cardnumber like ? ORDER BY $orderby";
165 @bind = ("$searchstring%","$searchstring");
167 else # advanced search looking in surname, firstname and othernames
169 @data = split( ' ', $searchstring );
171 $query = "SELECT * FROM borrowers
172 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
173 WHERE ((surname LIKE ? OR surname LIKE ?
174 OR firstname LIKE ? OR firstname LIKE ?
175 OR othernames LIKE ? OR othernames LIKE ?)
177 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
179 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
180 "$data[0]%", "% $data[0]%"
182 for ( my $i = 1 ; $i < $count ; $i++ ) {
183 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
184 OR firstname LIKE ? OR firstname LIKE ?
185 OR othernames LIKE ? OR othernames LIKE ?)";
187 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
188 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
192 $query = $query . ") OR cardnumber LIKE ?
194 push( @bind, $searchstring );
199 my $sth = $dbh->prepare($query);
201 # warn "Q $orderby : $query";
202 $sth->execute(@bind);
204 my $data = $sth->fetchall_arrayref({});
207 return ( scalar(@$data), $data );
210 =head2 GetMemberDetails
212 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
214 Looks up a patron and returns information about him or her. If
215 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
216 up the borrower by number; otherwise, it looks up the borrower by card
219 C<$borrower> is a reference-to-hash whose keys are the fields of the
220 borrowers table in the Koha database. In addition,
221 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
222 about the patron. Its keys act as flags :
224 if $borrower->{flags}->{LOST} {
225 # Patron's card was reported lost
228 Each flag has a C<message> key, giving a human-readable explanation of
229 the flag. If the state of a flag means that the patron should not be
230 allowed to borrow any more books, then it will have a C<noissues> key
233 The possible flags are:
239 =item Shows the patron's credit or debt, if any.
247 =item (Gone, no address.) Set if the patron has left without giving a
256 =item Set if the patron's card has been reported as lost.
264 =item Set if the patron has been debarred.
272 =item Any additional notes about the patron.
280 =item Set if the patron has overdue items. This flag has several keys:
282 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
283 overdue items. Its elements are references-to-hash, each describing an
284 overdue item. The keys are selected fields from the issues, biblio,
285 biblioitems, and items tables of the Koha database.
287 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
288 the overdue items, one per line.
296 =item Set if any items that the patron has reserved are available.
298 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
299 available items. Each element is a reference-to-hash whose keys are
300 fields from the reserves table of the Koha database.
306 sub GetMemberDetails {
307 my ( $borrowernumber, $cardnumber ) = @_;
308 my $dbh = C4::Context->dbh;
311 if ($borrowernumber) {
312 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
313 $sth->execute($borrowernumber);
315 elsif ($cardnumber) {
316 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
317 $sth->execute($cardnumber);
322 my $borrower = $sth->fetchrow_hashref;
323 my ($amount) = GetMemberAccountRecords( $borrowernumber);
324 $borrower->{'amountoutstanding'} = $amount;
325 my $flags = patronflags( $borrower);
328 $sth = $dbh->prepare("select bit,flag from userflags");
330 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
331 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
332 $accessflagshash->{$flag} = 1;
336 $borrower->{'flags'} = $flags;
337 $borrower->{'authflags'} = $accessflagshash;
339 # find out how long the membership lasts
342 "select enrolmentperiod from categories where categorycode = ?");
343 $sth->execute( $borrower->{'categorycode'} );
344 my $enrolment = $sth->fetchrow;
345 $borrower->{'enrolmentperiod'} = $enrolment;
346 return ($borrower); #, $flags, $accessflagshash);
353 NOTE!: If you change this function, be sure to update the POD for
356 $flags = &patronflags($patron);
359 {message} Message showing patron's credit or debt
360 {noissues} Set if patron owes >$5.00
361 {GNA} Set if patron gone w/o address
362 {message} "Borrower has no valid address"
364 {LOST} Set if patron's card reported lost
365 {message} Message to this effect
367 {DBARRED} Set is patron is debarred
368 {message} Message to this effect
370 {NOTES} Set if patron has notes
371 {message} Notes about patron
372 {ODUES} Set if patron has overdue books
374 {itemlist} ref-to-array: list of overdue books
375 {itemlisttext} Text list of overdue items
376 {WAITING} Set if there are items available that the
378 {message} Message to this effect
379 {itemlist} ref-to-array: list of available items
385 my ( $patroninformation) = @_;
386 my $dbh=C4::Context->dbh;
387 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
390 my $noissuescharge = C4::Context->preference("noissuescharge");
391 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
392 if ( $amount > $noissuescharge ) {
393 $flaginfo{'noissues'} = 1;
395 $flags{'CHARGES'} = \%flaginfo;
397 elsif ( $amount < 0 ) {
399 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
400 $flags{'CHARGES'} = \%flaginfo;
402 if ( $patroninformation->{'gonenoaddress'}
403 && $patroninformation->{'gonenoaddress'} == 1 )
406 $flaginfo{'message'} = 'Borrower has no valid address.';
407 $flaginfo{'noissues'} = 1;
408 $flags{'GNA'} = \%flaginfo;
410 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
412 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
413 $flaginfo{'noissues'} = 1;
414 $flags{'LOST'} = \%flaginfo;
416 if ( $patroninformation->{'debarred'}
417 && $patroninformation->{'debarred'} == 1 )
420 $flaginfo{'message'} = 'Borrower is Debarred.';
421 $flaginfo{'noissues'} = 1;
422 $flags{'DBARRED'} = \%flaginfo;
424 if ( $patroninformation->{'borrowernotes'}
425 && $patroninformation->{'borrowernotes'} )
428 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
429 $flags{'NOTES'} = \%flaginfo;
431 my ( $odues, $itemsoverdue ) =
432 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
435 $flaginfo{'message'} = "Yes";
436 $flaginfo{'itemlist'} = $itemsoverdue;
437 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
440 $flaginfo{'itemlisttext'} .=
441 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
443 $flags{'ODUES'} = \%flaginfo;
445 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
446 my $nowaiting = scalar @itemswaiting;
447 if ( $nowaiting > 0 ) {
449 $flaginfo{'message'} = "Reserved items available";
450 $flaginfo{'itemlist'} = \@itemswaiting;
451 $flags{'WAITING'} = \%flaginfo;
459 $borrower = &GetMember($information, $type);
461 Looks up information about a patron (borrower) by either card number
462 ,firstname, or borrower number, depending on $type value.
463 If C<$type> == 'cardnumber', C<&GetBorrower>
464 searches by cardnumber then by firstname if not found in cardnumber;
465 otherwise, it searches by borrowernumber.
467 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
468 the C<borrowers> table in the Koha database.
474 my ( $information, $type ) = @_;
475 my $dbh = C4::Context->dbh;
477 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
478 $information = uc $information;
481 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where $type=?"
483 $sth->execute($information);
488 "Select borrowers.*,categories.category_type, categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
490 $sth->execute($information);
492 my $data = $sth->fetchrow_hashref;
498 elsif ($type eq 'cardnumber' ||$type eq 'firstname') { # try with firstname
501 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where firstname like ?"
503 $sth->execute($information);
504 my $data = $sth->fetchrow_hashref;
513 =item GetMemberIssuesAndFines
515 ($borrowed, $due, $fine) = &GetMemberIssuesAndFines($borrowernumber);
517 Returns aggregate data about items borrowed by the patron with the
518 given borrowernumber.
520 C<&GetMemberIssuesAndFines> returns a three-element array. C<$borrowed> is the
521 number of books the patron currently has borrowed. C<$due> is the
522 number of overdue items the patron currently has borrowed. C<$fine> is
523 the total fine currently due by the borrower.
528 sub GetMemberIssuesAndFines {
529 my ( $borrowernumber ) = @_;
530 my $dbh = C4::Context->dbh;
532 "Select count(*) from issues where borrowernumber='$borrowernumber' and
536 my $sth = $dbh->prepare($query);
538 my $data = $sth->fetchrow_hashref;
540 $sth = $dbh->prepare(
541 "Select count(*) from issues where
542 borrowernumber='$borrowernumber' and date_due < now() and returndate is NULL"
545 my $data2 = $sth->fetchrow_hashref;
547 $sth = $dbh->prepare(
548 "Select sum(amountoutstanding) from accountlines where
549 borrowernumber='$borrowernumber'"
552 my $data3 = $sth->fetchrow_hashref;
555 return ( $data2->{'count(*)'}, $data->{'count(*)'},
556 $data3->{'sum(amountoutstanding)'} );
563 &ModMember($borrowernumber);
565 Modify borrower's data
572 my $dbh = C4::Context->dbh;
573 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} ) if ($data{'dateofbirth'} );
574 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} ) if ($data{'dateexpiry'} );
575 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
576 # warn Data::Dumper::Dumper(%data);
577 # warn "num user".$data{'borrowernumber'};
578 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
580 my %hashborrowerfields;
581 while (my ($field)=$qborrower->fetchrow){
582 $hashborrowerfields{$field}=1;
586 $data{'userid'} = '' if ( $data{'password'} eq '' );
589 # test to know if u must update or not the borrower password
590 if ( $data{'password'} eq '****' ) {
591 delete $data{'password'};
593 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_}) } ;
594 $query = "UPDATE borrowers SET ".join (",",@parameters)
595 ." WHERE borrowernumber=$data{'borrowernumber'}";
597 $sth = $dbh->prepare($query);
601 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne '' );
602 delete $data{'password'} if ($data{password} eq "");
604 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_})} ;
606 $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
608 $sth = $dbh->prepare($query);
613 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
614 # so when we update information for an adult we should check for guarantees and update the relevant part
615 # of their records, ie addresses and phone numbers
616 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
617 if ( $borrowercategory->{'category_type'} eq 'A' ) {
618 # is adult check guarantees;
619 UpdateGuarantees(%data);
622 &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"")
623 if C4::Context->preference("BorrowersLog");
631 $borrowernumber = &AddMember(%borrower);
633 insert new borrower into table
634 Returns the borrowernumber
641 my $dbh = C4::Context->dbh;
642 $data{'userid'} = '' unless $data{'password'};
643 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
644 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
645 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
646 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
648 "insert into borrowers set cardnumber="
649 . $dbh->quote( $data{'cardnumber'} )
651 . $dbh->quote( $data{'surname'} )
653 . $dbh->quote( $data{'firstname'} )
655 . $dbh->quote( $data{'title'} )
657 . $dbh->quote( $data{'othernames'} )
659 . $dbh->quote( $data{'initials'} )
661 . $dbh->quote( $data{'streetnumber'} )
663 . $dbh->quote( $data{'streettype'} )
665 . $dbh->quote( $data{'address'} )
667 . $dbh->quote( $data{'address2'} )
669 . $dbh->quote( $data{'zipcode'} )
671 . $dbh->quote( $data{'city'} )
673 . $dbh->quote( $data{'phone'} )
675 . $dbh->quote( $data{'email'} )
677 . $dbh->quote( $data{'mobile'} )
679 . $dbh->quote( $data{'phonepro'} )
681 . $dbh->quote( $data{'opacnote'} )
683 . $dbh->quote( $data{'guarantorid'} )
685 . $dbh->quote( $data{'dateofbirth'} )
687 . $dbh->quote( $data{'branchcode'} )
689 . $dbh->quote( $data{'categorycode'} )
691 . $dbh->quote( $data{'dateenrolled'} )
693 . $dbh->quote( $data{'contactname'} )
695 . $dbh->quote( $data{'borrowernotes'} )
697 . $dbh->quote( $data{'dateexpiry'} )
699 . $dbh->quote( $data{'contactnote'} )
701 . $dbh->quote( $data{'B_address'} )
703 . $dbh->quote( $data{'B_zipcode'} )
705 . $dbh->quote( $data{'B_city'} )
707 . $dbh->quote( $data{'B_phone'} )
709 . $dbh->quote( $data{'B_email'}, )
711 . $dbh->quote( $data{'password'} )
713 . $dbh->quote( $data{'userid'} )
715 . $dbh->quote( $data{'sort1'} )
717 . $dbh->quote( $data{'sort2'} )
719 . $dbh->quote( $data{'contacttitle'} )
721 . $dbh->quote( $data{'emailpro'} )
722 . ",contactfirstname="
723 . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
724 . $dbh->quote( $data{'sex'} ) . ",fax="
725 . $dbh->quote( $data{'fax'} )
727 . $dbh->quote( $data{'relationship'} )
729 . $dbh->quote( $data{'B_streetnumber'} )
731 . $dbh->quote( $data{'B_streettype'} )
733 . $dbh->quote( $data{'gonenoaddress'} )
735 . $dbh->quote( $data{'lost'} )
737 . $dbh->quote( $data{'debarred'} )
739 . $dbh->quote( $data{'ethnicity'} )
741 . $dbh->quote( $data{'ethnotes'} );
743 my $sth = $dbh->prepare($query);
746 $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
748 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"")
749 if C4::Context->preference("BorrowersLog");
751 return $data{'borrowernumber'};
755 my ($uid,$member) = @_;
756 my $dbh = C4::Context->dbh;
757 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
758 # Then we need to tell the user and have them create a new one.
761 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
762 $sth->execute( $uid, $member );
763 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
773 my ( $uid, $member, $digest ) = @_;
774 my $dbh = C4::Context->dbh;
776 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
777 #Then we need to tell the user and have them create a new one.
780 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
781 $sth->execute( $uid, $member );
782 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
786 #Everything is good so we can update the information.
789 "update borrowers set userid=?, password=? where borrowernumber=?");
790 $sth->execute( $uid, $digest, $member );
794 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"")
795 if C4::Context->preference("BorrowersLog");
800 =item fixup_cardnumber
802 Warning: The caller is responsible for locking the members table in write
803 mode, to avoid database corruption.
807 use vars qw( @weightings );
808 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
810 sub fixup_cardnumber ($) {
811 my ($cardnumber) = @_;
812 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
813 $autonumber_members = 0 unless defined $autonumber_members;
815 # Find out whether member numbers should be generated
816 # automatically. Should be either "1" or something else.
817 # Defaults to "0", which is interpreted as "no".
819 # if ($cardnumber !~ /\S/ && $autonumber_members) {
820 if ($autonumber_members) {
821 my $dbh = C4::Context->dbh;
822 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
824 # if checkdigit is selected, calculate katipo-style cardnumber.
825 # otherwise, just use the max()
826 # purpose: generate checksum'd member numbers.
827 # We'll assume we just got the max value of digits 2-8 of member #'s
828 # from the database and our job is to increment that by one,
829 # determine the 1st and 9th digits and return the full string.
832 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
836 my $data = $sth->fetchrow_hashref;
837 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
839 if ( !$cardnumber ) { # If DB has no values,
840 $cardnumber = 1000000; # start at 1000000
847 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
849 # read weightings, left to right, 1 char at a time
850 my $temp1 = $weightings[$i];
852 # sequence left to right, 1 char at a time
853 my $temp2 = substr( $cardnumber, $i, 1 );
855 # mult each char 1-7 by its corresponding weighting
856 $sum += $temp1 * $temp2;
859 my $rem = ( $sum % 11 );
860 $rem = 'X' if $rem == 10;
862 $cardnumber = "V$cardnumber$rem";
866 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
867 # better. I'll leave the original in in case it needs to be changed for you
870 "select max(cast(cardnumber as signed)) from borrowers");
872 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
876 my ($result) = $sth->fetchrow;
878 $cardnumber = $result + 1;
886 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
887 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
888 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
890 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
891 with children) and looks up the borrowers who are guaranteed by that
892 borrower (i.e., the patron's children).
894 C<&GetGuarantees> returns two values: an integer giving the number of
895 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
896 of references to hash, which gives the actual results.
902 my ($borrowernumber) = @_;
903 my $dbh = C4::Context->dbh;
906 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
908 $sth->execute($borrowernumber);
911 my $data = $sth->fetchall_arrayref({});
913 return ( scalar(@$data), $data );
916 =head2 UpdateGuarantees
918 &UpdateGuarantees($parent_borrno);
921 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
922 with the modified information
927 sub UpdateGuarantees {
929 my $dbh = C4::Context->dbh;
930 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
931 for ( my $i = 0 ; $i < $count ; $i++ ) {
934 # It looks like the $i is only being returned to handle walking through
935 # the array, which is probably better done as a foreach loop.
937 my $guaquery = qq|UPDATE borrowers
938 SET address='$data{'address'}',fax='$data{'fax'}',
939 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
940 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
942 my $sth3 = $dbh->prepare($guaquery);
947 =head2 GetPendingIssues
949 ($count, $issues) = &GetPendingIssues($borrowernumber);
951 Looks up what the patron with the given borrowernumber has borrowed.
953 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
954 reference-to-array, where each element is a reference-to-hash; the
955 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
956 in the Koha database. C<$count> is the number of elements in
962 sub GetPendingIssues {
963 my ($borrowernumber) = @_;
964 my $dbh = C4::Context->dbh;
966 my $sth = $dbh->prepare(
967 "SELECT * FROM issues
968 LEFT JOIN items ON issues.itemnumber=items.itemnumber
969 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
970 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
973 AND returndate IS NULL
974 ORDER BY issues.issuedate"
976 $sth->execute($borrowernumber);
977 my $data = $sth->fetchall_arrayref({});
978 my $today = POSIX::strftime("%Y%m%d", localtime);
980 my $datedue = $_->{'date_due'};
982 if ( $datedue < $today ) {
987 return ( scalar(@$data), $data );
992 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
994 Looks up what the patron with the given borrowernumber has borrowed,
995 and sorts the results.
997 C<$sortkey> is the name of a field on which to sort the results. This
998 should be the name of a field in the C<issues>, C<biblio>,
999 C<biblioitems>, or C<items> table in the Koha database.
1001 C<$limit> is the maximum number of results to return.
1003 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1004 reference-to-array, where each element is a reference-to-hash; the
1005 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1006 C<items> tables of the Koha database. C<$count> is the number of
1007 elements in C<$issues>
1013 my ( $borrowernumber, $order, $limit ) = @_;
1015 #FIXME: sanity-check order and limit
1016 my $dbh = C4::Context->dbh;
1019 "Select *,items.timestamp AS itemstimestamp from issues,biblio,items,biblioitems
1020 where borrowernumber=? and
1021 items.biblioitemnumber=biblioitems.biblioitemnumber and
1022 items.itemnumber=issues.itemnumber and
1023 items.biblionumber=biblio.biblionumber order by $order";
1024 if ( $limit != 0 ) {
1025 $query .= " limit $limit";
1029 my $sth = $dbh->prepare($query);
1030 $sth->execute($borrowernumber);
1033 while ( my $data = $sth->fetchrow_hashref ) {
1034 $result[$i] = $data;
1039 # get all issued items for borrowernumber from oldissues table
1040 # large chunk of older issues data put into table oldissues
1041 # to speed up db calls for issuing items
1042 if ( C4::Context->preference("ReadingHistory") ) {
1043 my $query2 = "SELECT * FROM oldissues,biblio,items,biblioitems
1044 WHERE borrowernumber=?
1045 AND items.biblioitemnumber=biblioitems.biblioitemnumber
1046 AND items.itemnumber=oldissues.itemnumber
1047 AND items.biblionumber=biblio.biblionumber
1049 if ( $limit != 0 ) {
1050 $limit = $limit - $count;
1051 $query2 .= " limit $limit";
1054 my $sth2 = $dbh->prepare($query2);
1055 $sth2->execute($borrowernumber);
1057 while ( my $data2 = $sth2->fetchrow_hashref ) {
1058 $result[$i] = $data2;
1065 return ( $i, \@result );
1069 =head2 GetMemberAccountRecords
1071 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1073 Looks up accounting data for the patron with the given borrowernumber.
1075 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1076 reference-to-array, where each element is a reference-to-hash; the
1077 keys are the fields of the C<accountlines> table in the Koha database.
1078 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1079 total amount outstanding for all of the account lines.
1084 sub GetMemberAccountRecords {
1085 my ($borrowernumber,$date) = @_;
1086 my $dbh = C4::Context->dbh;
1092 WHERE borrowernumber=?);
1093 my @bind = ($borrowernumber);
1094 if ($date && $date ne ''){
1100 ORDER BY date desc,timestamp DESC";
1101 my $sth= $dbh->prepare( $strsth );
1102 $sth->execute( @bind );
1104 while ( my $data = $sth->fetchrow_hashref ) {
1105 $acctlines[$numlines] = $data;
1107 $total += $data->{'amountoutstanding'};
1110 return ( $total, \@acctlines,$numlines);
1113 =head2 GetBorNotifyAcctRecord
1115 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1117 Looks up accounting data for the patron with the given borrowernumber per file number.
1119 (FIXME - I'm not at all sure what this is about.)
1121 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1122 reference-to-array, where each element is a reference-to-hash; the
1123 keys are the fields of the C<accountlines> table in the Koha database.
1124 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1125 total amount outstanding for all of the account lines.
1129 sub GetBorNotifyAcctRecord {
1130 my ( $borrowernumber, $notifyid ) = @_;
1131 my $dbh = C4::Context->dbh;
1134 my $query = qq| SELECT *
1136 WHERE borrowernumber=?
1138 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')
1139 AND amountoutstanding != '0'
1140 ORDER BY notify_id,accounttype
1142 my $sth = $dbh->prepare($query);
1144 $sth->execute( $borrowernumber, $notifyid );
1146 while ( my $data = $sth->fetchrow_hashref ) {
1147 $acctlines[$numlines] = $data;
1149 $total += $data->{'amountoutstanding'};
1152 return ( $total, \@acctlines, $numlines );
1155 =head2 checkuniquemember (OUEST-PROVENCE)
1157 $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1159 Checks that a member exists or not in the database.
1161 C<&result> is 1 (=exist) or 0 (=does not exist)
1162 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1163 C<&surname> is the surname
1164 C<&categorycode> is from categorycode table
1165 C<&firstname> is the firstname (only if collectivity=0)
1166 C<&dateofbirth> is the date of birth (only if collectivity=0)
1170 sub checkuniquemember {
1171 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1172 my $dbh = C4::Context->dbh;
1174 if ($collectivity) {
1176 # $request="select count(*) from borrowers where surname=? and categorycode=?";
1178 "select borrowernumber,categorycode from borrowers where surname=? ";
1182 # $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1184 "select borrowernumber,categorycode from borrowers where surname=? and firstname=? and dateofbirth=?";
1186 my $sth = $dbh->prepare($request);
1187 if ($collectivity) {
1188 $sth->execute( uc($surname) );
1191 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1193 my @data = $sth->fetchrow;
1196 return $data[0], $data[1];
1206 sub checkcardnumber {
1207 my ($cardnumber) = @_;
1208 my $dbh = C4::Context->dbh;
1209 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1210 my $sth = $dbh->prepare($query);
1211 $sth->execute($cardnumber);
1212 if (my $data= $sth->fetchrow_hashref()){
1222 =head2 getzipnamecity (OUEST-PROVENCE)
1224 take all info from table city for the fields city and zip
1225 check for the name and the zip code of the city selected
1229 sub getzipnamecity {
1231 my $dbh = C4::Context->dbh;
1234 "select city_name,city_zipcode from cities where cityid=? ");
1235 $sth->execute($cityid);
1236 my @data = $sth->fetchrow;
1237 return $data[0], $data[1];
1241 =head2 getdcity (OUEST-PROVENCE)
1243 recover cityid with city_name condition
1248 my ($city_name) = @_;
1249 my $dbh = C4::Context->dbh;
1250 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1251 $sth->execute($city_name);
1252 my $data = $sth->fetchrow;
1257 =head2 GetExpiryDate
1259 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1260 process expiry date given a date and a categorycode
1264 my ( $categorycode, $dateenrolled ) = @_;
1265 my $dbh = C4::Context->dbh;
1268 "select enrolmentperiod from categories where categorycode=?");
1269 $sth->execute($categorycode);
1270 my ($enrolmentperiod) = $sth->fetchrow;
1271 $enrolmentperiod = 12 unless ($enrolmentperiod);
1272 my @date=split /-/,format_date_in_iso($dateenrolled);
1273 @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1274 return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1277 =head2 checkuserpassword (OUEST-PROVENCE)
1279 check for the password and login are not used
1280 return the number of record
1281 0=> NOT USED 1=> USED
1285 sub checkuserpassword {
1286 my ( $borrowernumber, $userid, $password ) = @_;
1287 $password = md5_base64($password);
1288 my $dbh = C4::Context->dbh;
1291 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1293 $sth->execute( $borrowernumber, $userid, $password );
1294 my $number_rows = $sth->fetchrow;
1295 return $number_rows;
1299 =head2 GetborCatFromCatType
1301 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1303 Looks up the different types of borrowers in the database. Returns two
1304 elements: a reference-to-array, which lists the borrower category
1305 codes, and a reference-to-hash, which maps the borrower category codes
1306 to category descriptions.
1311 sub GetborCatFromCatType {
1312 my ( $category_type, $action ) = @_;
1313 my $dbh = C4::Context->dbh;
1314 my $request = qq| SELECT categorycode,description
1317 ORDER BY categorycode|;
1318 my $sth = $dbh->prepare($request);
1320 $sth->execute($category_type);
1329 while ( my $data = $sth->fetchrow_hashref ) {
1330 push @codes, $data->{'categorycode'};
1331 $labels{ $data->{'categorycode'} } = $data->{'description'};
1334 return ( \@codes, \%labels );
1337 =head2 GetBorrowercategory
1339 $hashref = &GetBorrowercategory($categorycode);
1341 Given the borrower's category code, the function returns the corresponding
1342 data hashref for a comprehensive information display.
1346 sub GetBorrowercategory {
1348 my $dbh = C4::Context->dbh;
1351 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1353 WHERE categorycode = ?"
1355 $sth->execute($catcode);
1357 $sth->fetchrow_hashref;
1360 } # sub getborrowercategory
1362 =head2 ethnicitycategories
1364 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1366 Looks up the different ethnic types in the database. Returns two
1367 elements: a reference-to-array, which lists the ethnicity codes, and a
1368 reference-to-hash, which maps the ethnicity codes to ethnicity
1375 sub ethnicitycategories {
1376 my $dbh = C4::Context->dbh;
1377 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1381 while ( my $data = $sth->fetchrow_hashref ) {
1382 push @codes, $data->{'code'};
1383 $labels{ $data->{'code'} } = $data->{'name'};
1386 return ( \@codes, \%labels );
1391 $ethn_name = &fixEthnicity($ethn_code);
1393 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1394 corresponding descriptive name from the C<ethnicity> table in the
1395 Koha database ("European" or "Pacific Islander").
1402 my $ethnicity = shift;
1403 return unless $ethnicity;
1404 my $dbh = C4::Context->dbh;
1405 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1406 $sth->execute($ethnicity);
1407 my $data = $sth->fetchrow_hashref;
1409 return $data->{'name'};
1410 } # sub fixEthnicity
1414 $dateofbirth,$date = &GetAge($date);
1416 this function return the borrowers age with the value of dateofbirth
1422 my ( $date, $date_ref ) = @_;
1424 if ( not defined $date_ref ) {
1425 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1428 my ( $year1, $month1, $day1 ) = split /-/, $date;
1429 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1431 my $age = $year2 - $year1;
1432 if ( $month1 . $day1 > $month2 . $day2 ) {
1439 =head2 get_institutions
1440 $insitutions = get_institutions();
1442 Just returns a list of all the borrowers of type I, borrownumber and name
1447 sub get_institutions {
1448 my $dbh = C4::Context->dbh();
1451 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1455 while ( my $data = $sth->fetchrow_hashref() ) {
1456 $orgs{ $data->{'borrowernumber'} } = $data;
1461 } # sub get_institutions
1463 =head2 add_member_orgs
1465 add_member_orgs($borrowernumber,$borrowernumbers);
1467 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1472 sub add_member_orgs {
1473 my ( $borrowernumber, $otherborrowers ) = @_;
1474 my $dbh = C4::Context->dbh();
1476 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1477 my $sth = $dbh->prepare($query);
1478 foreach my $otherborrowernumber (@$otherborrowers) {
1479 $sth->execute( $borrowernumber, $otherborrowernumber );
1483 } # sub add_member_orgs
1485 =head2 GetCities (OUEST-PROVENCE)
1487 ($id_cityarrayref, $city_hashref) = &GetCities();
1489 Looks up the different city and zip in the database. Returns two
1490 elements: a reference-to-array, which lists the zip city
1491 codes, and a reference-to-hash, which maps the name of the city.
1492 WHERE =>OUEST PROVENCE OR EXTERIEUR
1498 #my ($type_city) = @_;
1499 my $dbh = C4::Context->dbh;
1500 my $query = qq|SELECT cityid,city_name
1502 ORDER BY city_name|;
1503 my $sth = $dbh->prepare($query);
1505 #$sth->execute($type_city);
1510 # insert empty value to create a empty choice in cgi popup
1512 while ( my $data = $sth->fetchrow_hashref ) {
1514 push @id, $data->{'cityid'};
1515 $city{ $data->{'cityid'} } = $data->{'city_name'};
1518 #test to know if the table contain some records if no the function return nothing
1526 return ( \@id, \%city );
1530 =head2 GetSortDetails (OUEST-PROVENCE)
1532 ($lib) = &GetSortDetails($category,$sortvalue);
1534 Returns the authorized value details
1535 C<&$lib>return value of authorized value details
1536 C<&$sortvalue>this is the value of authorized value
1537 C<&$category>this is the value of authorized value category
1541 sub GetSortDetails {
1542 my ( $category, $sortvalue ) = @_;
1543 my $dbh = C4::Context->dbh;
1544 my $query = qq|SELECT lib
1545 FROM authorised_values
1547 AND authorised_value=? |;
1548 my $sth = $dbh->prepare($query);
1549 $sth->execute( $category, $sortvalue );
1550 my $lib = $sth->fetchrow;
1554 =head2 DeleteBorrower
1556 () = &DeleteBorrower($member);
1558 delete all data fo borrowers and add record to deletedborrowers table
1559 C<&$member>this is the borrowernumber
1563 sub MoveMemberToDeleted {
1565 my $dbh = C4::Context->dbh;
1567 $query = qq|SELECT *
1569 WHERE borrowernumber=?|;
1570 my $sth = $dbh->prepare($query);
1571 $sth->execute($member);
1572 my @data = $sth->fetchrow_array;
1575 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1576 . ( "?," x ( scalar(@data) - 1 ) )
1578 $sth->execute(@data);
1584 DelMember($borrowernumber);
1586 This function remove directly a borrower whitout writing it on deleteborrower.
1587 + Deletes reserves for the borrower
1592 my $dbh = C4::Context->dbh;
1593 my $borrowernumber = shift;
1594 warn "in delmember with $borrowernumber";
1595 return unless $borrowernumber; # borrowernumber is mandatory.
1597 my $query = qq|DELETE
1599 WHERE borrowernumber=?|;
1600 my $sth = $dbh->prepare($query);
1601 $sth->execute($borrowernumber);
1606 WHERE borrowernumber = ?
1608 $sth = $dbh->prepare($query);
1609 $sth->execute($borrowernumber);
1611 &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"")
1612 if C4::Context->preference("BorrowersLog");
1616 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1618 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1619 Extending the subscription to a given date or to the expiry date calculated on local date.
1623 sub ExtendMemberSubscriptionTo {
1624 my ( $borrowerid,$date) = @_;
1625 my $dbh = C4::Context->dbh;
1627 $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1628 my $borrower = GetMember($borrowerid,'borrowernumber');
1629 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1631 my $sth = $dbh->do(<<EOF);
1633 SET dateexpiry='$date'
1634 WHERE borrowernumber='$borrowerid'
1636 return $date if ($sth);
1640 =head2 GetRoadTypes (OUEST-PROVENCE)
1642 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1644 Looks up the different road type . Returns two
1645 elements: a reference-to-array, which lists the id_roadtype
1646 codes, and a reference-to-hash, which maps the road type of the road .
1652 my $dbh = C4::Context->dbh;
1654 SELECT roadtypeid,road_type
1656 ORDER BY road_type|;
1657 my $sth = $dbh->prepare($query);
1662 # insert empty value to create a empty choice in cgi popup
1664 while ( my $data = $sth->fetchrow_hashref ) {
1666 push @id, $data->{'roadtypeid'};
1667 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1670 #test to know if the table contain some records if no the function return nothing
1678 return ( \@id, \%roadtype );
1684 =head2 GetTitles (OUEST-PROVENCE)
1686 ($borrowertitle)= &GetTitles();
1688 Looks up the different title . Returns array with all borrowers title
1693 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1694 unshift( @borrowerTitle, "" );
1695 return ( \@borrowerTitle);
1700 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1702 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1704 Returns the description of roadtype
1705 C<&$roadtype>return description of road type
1706 C<&$roadtypeid>this is the value of roadtype s
1710 sub GetRoadTypeDetails {
1711 my ($roadtypeid) = @_;
1712 my $dbh = C4::Context->dbh;
1716 WHERE roadtypeid=?|;
1717 my $sth = $dbh->prepare($query);
1718 $sth->execute($roadtypeid);
1719 my $roadtype = $sth->fetchrow;
1723 =head2 GetBorrowersWhoHaveNotBorrowedSince
1725 &GetBorrowersWhoHaveNotBorrowedSince($date)
1727 this function get all borrowers who haven't borrowed since the date given on input arg.
1731 sub GetBorrowersWhoHaveNotBorrowedSince {
1733 return unless $date; # date is mandatory.
1734 my $dbh = C4::Context->dbh;
1736 SELECT borrowers.borrowernumber,max(timestamp)
1738 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1739 WHERE issues.borrowernumber IS NOT NULL
1740 GROUP BY borrowers.borrowernumber
1742 my $sth = $dbh->prepare($query);
1746 while ( my $data = $sth->fetchrow_hashref ) {
1747 push @results, $data;
1752 =head2 GetBorrowersWhoHaveNeverBorrowed
1754 $results = &GetBorrowersWhoHaveNeverBorrowed
1756 this function get all borrowers who have never borrowed.
1758 I<$result> is a ref to an array which all elements are a hasref.
1762 sub GetBorrowersWhoHaveNeverBorrowed {
1763 my $dbh = C4::Context->dbh;
1765 SELECT borrowers.borrowernumber,max(timestamp)
1767 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1768 WHERE issues.borrowernumber IS NULL
1770 my $sth = $dbh->prepare($query);
1773 while ( my $data = $sth->fetchrow_hashref ) {
1774 push @results, $data;
1779 =head2 GetBorrowersWithIssuesHistoryOlderThan
1781 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1783 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1785 I<$result> is a ref to an array which all elements are a hashref.
1786 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1790 sub GetBorrowersWithIssuesHistoryOlderThan {
1791 my $dbh = C4::Context->dbh;
1793 return unless $date; # date is mandatory.
1795 SELECT count(borrowernumber) as n,borrowernumber
1797 WHERE returndate < ?
1798 AND borrowernumber IS NOT NULL
1799 GROUP BY borrowernumber
1801 my $sth = $dbh->prepare($query);
1802 $sth->execute($date);
1805 while ( my $data = $sth->fetchrow_hashref ) {
1806 push @results, $data;
1811 END { } # module clean-up code here (global destructor)