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
25 use Digest::MD5 qw(md5_base64);
26 use Date::Calc qw/Today Add_Delta_YM/;
27 use C4::Log; # logaction
31 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK);
37 C4::Members - Perl Module containing convenience functions for member handling
45 This module contains routines for adding, modifying and deleting members/patrons/borrowers
63 &GetMemberIssuesAndFines
78 &GetMemberAccountRecords
79 &GetBorNotifyAcctRecord
85 &GetBorrowersWhoHaveNotBorrowedSince
86 &GetBorrowersWhoHaveNeverBorrowed
87 &GetBorrowersWithIssuesHistoryOlderThan
108 &ExtendMemberSubscriptionTo
124 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
126 Looks up patrons (borrowers) by name.
128 BUGFIX 499: C<$type> is now used to determine type of search.
129 if $type is "simple", search is performed on the first letter of the
132 $category_type is used to get a specified type of user.
133 (mainly adults when creating a child.)
135 C<$searchstring> is a space-separated list of search terms. Each term
136 must match the beginning a borrower's surname, first name, or other
139 C<$filter> is assumed to be a list of elements to filter results on
141 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
143 C<&SearchMember> returns a two-element list. C<$borrowers> is a
144 reference-to-array; each element is a reference-to-hash, whose keys
145 are the fields of the C<borrowers> table in the Koha database.
146 C<$count> is the number of elements in C<$borrowers>.
151 #used by member enquiries from the intranet
154 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
155 my $dbh = C4::Context->dbh;
161 if ( $type eq "simple" ) # simple search for one letter only
166 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode ".
167 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
169 " WHERE (surname LIKE ? OR cardnumber like ?) ";
170 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
171 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
172 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
175 $query.=" ORDER BY $orderby";
176 @bind = ("$searchstring%","$searchstring");
178 else # advanced search looking in surname, firstname and othernames
180 @data = split( ' ', $searchstring );
182 $query = "SELECT * FROM borrowers
183 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
185 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
186 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
187 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
190 $query.="((surname LIKE ? OR surname LIKE ?
191 OR firstname LIKE ? OR firstname LIKE ?
192 OR othernames LIKE ? OR othernames LIKE ?)
194 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
196 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
197 "$data[0]%", "% $data[0]%"
199 for ( my $i = 1 ; $i < $count ; $i++ ) {
200 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
201 OR firstname LIKE ? OR firstname LIKE ?
202 OR othernames LIKE ? OR othernames LIKE ?)";
204 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
205 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
209 $query = $query . ") OR cardnumber LIKE ?
211 push( @bind, $searchstring );
216 my $sth = $dbh->prepare($query);
218 # warn "Q $orderby : $query";
219 $sth->execute(@bind);
221 my $data = $sth->fetchall_arrayref({});
224 return ( scalar(@$data), $data );
227 =head2 GetMemberDetails
229 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
231 Looks up a patron and returns information about him or her. If
232 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
233 up the borrower by number; otherwise, it looks up the borrower by card
236 C<$borrower> is a reference-to-hash whose keys are the fields of the
237 borrowers table in the Koha database. In addition,
238 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
239 about the patron. Its keys act as flags :
241 if $borrower->{flags}->{LOST} {
242 # Patron's card was reported lost
245 Each flag has a C<message> key, giving a human-readable explanation of
246 the flag. If the state of a flag means that the patron should not be
247 allowed to borrow any more books, then it will have a C<noissues> key
250 The possible flags are:
256 =item Shows the patron's credit or debt, if any.
264 =item (Gone, no address.) Set if the patron has left without giving a
273 =item Set if the patron's card has been reported as lost.
281 =item Set if the patron has been debarred.
289 =item Any additional notes about the patron.
297 =item Set if the patron has overdue items. This flag has several keys:
299 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
300 overdue items. Its elements are references-to-hash, each describing an
301 overdue item. The keys are selected fields from the issues, biblio,
302 biblioitems, and items tables of the Koha database.
304 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
305 the overdue items, one per line.
313 =item Set if any items that the patron has reserved are available.
315 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
316 available items. Each element is a reference-to-hash whose keys are
317 fields from the reserves table of the Koha database.
323 sub GetMemberDetails {
324 my ( $borrowernumber, $cardnumber ) = @_;
325 my $dbh = C4::Context->dbh;
328 if ($borrowernumber) {
329 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
330 $sth->execute($borrowernumber);
332 elsif ($cardnumber) {
333 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
334 $sth->execute($cardnumber);
339 my $borrower = $sth->fetchrow_hashref;
340 my ($amount) = GetMemberAccountRecords( $borrowernumber);
341 $borrower->{'amountoutstanding'} = $amount;
342 my $flags = patronflags( $borrower);
345 $sth = $dbh->prepare("select bit,flag from userflags");
347 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
348 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
349 $accessflagshash->{$flag} = 1;
353 $borrower->{'flags'} = $flags;
354 $borrower->{'authflags'} = $accessflagshash;
356 # find out how long the membership lasts
359 "select enrolmentperiod from categories where categorycode = ?");
360 $sth->execute( $borrower->{'categorycode'} );
361 my $enrolment = $sth->fetchrow;
362 $borrower->{'enrolmentperiod'} = $enrolment;
363 return ($borrower); #, $flags, $accessflagshash);
370 NOTE!: If you change this function, be sure to update the POD for
373 $flags = &patronflags($patron);
376 {message} Message showing patron's credit or debt
377 {noissues} Set if patron owes >$5.00
378 {GNA} Set if patron gone w/o address
379 {message} "Borrower has no valid address"
381 {LOST} Set if patron's card reported lost
382 {message} Message to this effect
384 {DBARRED} Set is patron is debarred
385 {message} Message to this effect
387 {NOTES} Set if patron has notes
388 {message} Notes about patron
389 {ODUES} Set if patron has overdue books
391 {itemlist} ref-to-array: list of overdue books
392 {itemlisttext} Text list of overdue items
393 {WAITING} Set if there are items available that the
395 {message} Message to this effect
396 {itemlist} ref-to-array: list of available items
402 my ( $patroninformation) = @_;
403 my $dbh=C4::Context->dbh;
404 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
407 my $noissuescharge = C4::Context->preference("noissuescharge");
408 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
409 if ( $amount > $noissuescharge ) {
410 $flaginfo{'noissues'} = 1;
412 $flags{'CHARGES'} = \%flaginfo;
414 elsif ( $amount < 0 ) {
416 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
417 $flags{'CHARGES'} = \%flaginfo;
419 if ( $patroninformation->{'gonenoaddress'}
420 && $patroninformation->{'gonenoaddress'} == 1 )
423 $flaginfo{'message'} = 'Borrower has no valid address.';
424 $flaginfo{'noissues'} = 1;
425 $flags{'GNA'} = \%flaginfo;
427 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
429 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
430 $flaginfo{'noissues'} = 1;
431 $flags{'LOST'} = \%flaginfo;
433 if ( $patroninformation->{'debarred'}
434 && $patroninformation->{'debarred'} == 1 )
437 $flaginfo{'message'} = 'Borrower is Debarred.';
438 $flaginfo{'noissues'} = 1;
439 $flags{'DBARRED'} = \%flaginfo;
441 if ( $patroninformation->{'borrowernotes'}
442 && $patroninformation->{'borrowernotes'} )
445 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
446 $flags{'NOTES'} = \%flaginfo;
448 my ( $odues, $itemsoverdue ) =
449 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
452 $flaginfo{'message'} = "Yes";
453 $flaginfo{'itemlist'} = $itemsoverdue;
454 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
457 $flaginfo{'itemlisttext'} .=
458 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
460 $flags{'ODUES'} = \%flaginfo;
462 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
463 my $nowaiting = scalar @itemswaiting;
464 if ( $nowaiting > 0 ) {
466 $flaginfo{'message'} = "Reserved items available";
467 $flaginfo{'itemlist'} = \@itemswaiting;
468 $flags{'WAITING'} = \%flaginfo;
476 $borrower = &GetMember($information, $type);
478 Looks up information about a patron (borrower) by either card number
479 ,firstname, or borrower number, depending on $type value.
480 If C<$type> == 'cardnumber', C<&GetBorrower>
481 searches by cardnumber then by firstname if not found in cardnumber;
482 otherwise, it searches by borrowernumber.
484 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
485 the C<borrowers> table in the Koha database.
491 my ( $information, $type ) = @_;
492 my $dbh = C4::Context->dbh;
494 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
495 $information = uc $information;
498 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where $type=?"
500 $sth->execute($information);
505 "Select borrowers.*,categories.category_type, categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
507 $sth->execute($information);
509 my $data = $sth->fetchrow_hashref;
515 elsif ($type eq 'cardnumber' ||$type eq 'firstname') { # try with firstname
518 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where firstname like ?"
520 $sth->execute($information);
521 my $data = $sth->fetchrow_hashref;
530 =item GetMemberIssuesAndFines
532 ($borrowed, $due, $fine) = &GetMemberIssuesAndFines($borrowernumber);
534 Returns aggregate data about items borrowed by the patron with the
535 given borrowernumber.
537 C<&GetMemberIssuesAndFines> returns a three-element array. C<$borrowed> is the
538 number of books the patron currently has borrowed. C<$due> is the
539 number of overdue items the patron currently has borrowed. C<$fine> is
540 the total fine currently due by the borrower.
545 sub GetMemberIssuesAndFines {
546 my ( $borrowernumber ) = @_;
547 my $dbh = C4::Context->dbh;
549 "Select count(*) from issues where borrowernumber='$borrowernumber' and
553 my $sth = $dbh->prepare($query);
555 my $data = $sth->fetchrow_hashref;
557 $sth = $dbh->prepare(
558 "Select count(*) from issues where
559 borrowernumber='$borrowernumber' and date_due < now() and returndate is NULL"
562 my $data2 = $sth->fetchrow_hashref;
564 $sth = $dbh->prepare(
565 "Select sum(amountoutstanding) from accountlines where
566 borrowernumber='$borrowernumber'"
569 my $data3 = $sth->fetchrow_hashref;
572 return ( $data2->{'count(*)'}, $data->{'count(*)'},
573 $data3->{'sum(amountoutstanding)'} );
580 &ModMember($borrowernumber);
582 Modify borrower's data
589 my $dbh = C4::Context->dbh;
590 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} ) if ($data{'dateofbirth'} );
591 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} ) if ($data{'dateexpiry'} );
592 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
593 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
595 my %hashborrowerfields;
596 while (my ($field)=$qborrower->fetchrow){
597 $hashborrowerfields{$field}=1;
603 # test to know if u must update or not the borrower password
604 if ( $data{'password'} eq '****' ) {
605 delete $data{'password'};
607 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $_ ne "flags" and $hashborrowerfields{$_}) } ;
608 $query = "UPDATE borrowers SET ".join (",",@parameters)
609 ." WHERE borrowernumber=$data{'borrowernumber'}";
611 $sth = $dbh->prepare($query);
615 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne '' );
616 delete $data{'password'} if ($data{password} eq "");
618 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $_ ne "flags" and $hashborrowerfields{$_})} ;
620 $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
622 $sth = $dbh->prepare($query);
627 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
628 # so when we update information for an adult we should check for guarantees and update the relevant part
629 # of their records, ie addresses and phone numbers
630 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
631 if ( $borrowercategory->{'category_type'} eq 'A' ) {
632 # is adult check guarantees;
633 UpdateGuarantees(%data);
636 &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"")
637 if C4::Context->preference("BorrowersLog");
645 $borrowernumber = &AddMember(%borrower);
647 insert new borrower into table
648 Returns the borrowernumber
655 my $dbh = C4::Context->dbh;
656 $data{'userid'} = '' unless $data{'password'};
657 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
658 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
659 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
660 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
662 "insert into borrowers set cardnumber="
663 . $dbh->quote( $data{'cardnumber'} )
665 . $dbh->quote( $data{'surname'} )
667 . $dbh->quote( $data{'firstname'} )
669 . $dbh->quote( $data{'title'} )
671 . $dbh->quote( $data{'othernames'} )
673 . $dbh->quote( $data{'initials'} )
675 . $dbh->quote( $data{'streetnumber'} )
677 . $dbh->quote( $data{'streettype'} )
679 . $dbh->quote( $data{'address'} )
681 . $dbh->quote( $data{'address2'} )
683 . $dbh->quote( $data{'zipcode'} )
685 . $dbh->quote( $data{'city'} )
687 . $dbh->quote( $data{'phone'} )
689 . $dbh->quote( $data{'email'} )
691 . $dbh->quote( $data{'mobile'} )
693 . $dbh->quote( $data{'phonepro'} )
695 . $dbh->quote( $data{'opacnote'} )
697 . $dbh->quote( $data{'guarantorid'} )
699 . $dbh->quote( $data{'dateofbirth'} )
701 . $dbh->quote( $data{'branchcode'} )
703 . $dbh->quote( $data{'categorycode'} )
705 . $dbh->quote( $data{'dateenrolled'} )
707 . $dbh->quote( $data{'contactname'} )
709 . $dbh->quote( $data{'borrowernotes'} )
711 . $dbh->quote( $data{'dateexpiry'} )
713 . $dbh->quote( $data{'contactnote'} )
715 . $dbh->quote( $data{'B_address'} )
717 . $dbh->quote( $data{'B_zipcode'} )
719 . $dbh->quote( $data{'B_city'} )
721 . $dbh->quote( $data{'B_phone'} )
723 . $dbh->quote( $data{'B_email'}, )
725 . $dbh->quote( $data{'password'} )
727 . $dbh->quote( $data{'userid'} )
729 . $dbh->quote( $data{'sort1'} )
731 . $dbh->quote( $data{'sort2'} )
733 . $dbh->quote( $data{'contacttitle'} )
735 . $dbh->quote( $data{'emailpro'} )
736 . ",contactfirstname="
737 . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
738 . $dbh->quote( $data{'sex'} ) . ",fax="
739 . $dbh->quote( $data{'fax'} )
741 . $dbh->quote( $data{'relationship'} )
743 . $dbh->quote( $data{'B_streetnumber'} )
745 . $dbh->quote( $data{'B_streettype'} )
747 . $dbh->quote( $data{'gonenoaddress'} )
749 . $dbh->quote( $data{'lost'} )
751 . $dbh->quote( $data{'debarred'} )
753 . $dbh->quote( $data{'ethnicity'} )
755 . $dbh->quote( $data{'ethnotes'} );
757 my $sth = $dbh->prepare($query);
760 $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
762 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"")
763 if C4::Context->preference("BorrowersLog");
765 return $data{'borrowernumber'};
769 my ($uid,$member) = @_;
770 my $dbh = C4::Context->dbh;
771 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
772 # Then we need to tell the user and have them create a new one.
775 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
776 $sth->execute( $uid, $member );
777 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
787 my ( $uid, $member, $digest ) = @_;
788 my $dbh = C4::Context->dbh;
790 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
791 #Then we need to tell the user and have them create a new one.
794 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
795 $sth->execute( $uid, $member );
796 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
800 #Everything is good so we can update the information.
803 "update borrowers set userid=?, password=? where borrowernumber=?");
804 $sth->execute( $uid, $digest, $member );
808 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"")
809 if C4::Context->preference("BorrowersLog");
814 =item fixup_cardnumber
816 Warning: The caller is responsible for locking the members table in write
817 mode, to avoid database corruption.
821 use vars qw( @weightings );
822 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
824 sub fixup_cardnumber ($) {
825 my ($cardnumber) = @_;
826 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
827 $autonumber_members = 0 unless defined $autonumber_members;
829 # Find out whether member numbers should be generated
830 # automatically. Should be either "1" or something else.
831 # Defaults to "0", which is interpreted as "no".
833 # if ($cardnumber !~ /\S/ && $autonumber_members) {
834 if ($autonumber_members) {
835 my $dbh = C4::Context->dbh;
836 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
838 # if checkdigit is selected, calculate katipo-style cardnumber.
839 # otherwise, just use the max()
840 # purpose: generate checksum'd member numbers.
841 # We'll assume we just got the max value of digits 2-8 of member #'s
842 # from the database and our job is to increment that by one,
843 # determine the 1st and 9th digits and return the full string.
846 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
850 my $data = $sth->fetchrow_hashref;
851 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
853 if ( !$cardnumber ) { # If DB has no values,
854 $cardnumber = 1000000; # start at 1000000
861 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
863 # read weightings, left to right, 1 char at a time
864 my $temp1 = $weightings[$i];
866 # sequence left to right, 1 char at a time
867 my $temp2 = substr( $cardnumber, $i, 1 );
869 # mult each char 1-7 by its corresponding weighting
870 $sum += $temp1 * $temp2;
873 my $rem = ( $sum % 11 );
874 $rem = 'X' if $rem == 10;
876 $cardnumber = "V$cardnumber$rem";
880 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
881 # better. I'll leave the original in in case it needs to be changed for you
884 "select max(cast(cardnumber as signed)) from borrowers");
886 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
890 my ($result) = $sth->fetchrow;
892 $cardnumber = $result + 1;
900 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
901 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
902 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
904 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
905 with children) and looks up the borrowers who are guaranteed by that
906 borrower (i.e., the patron's children).
908 C<&GetGuarantees> returns two values: an integer giving the number of
909 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
910 of references to hash, which gives the actual results.
916 my ($borrowernumber) = @_;
917 my $dbh = C4::Context->dbh;
920 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
922 $sth->execute($borrowernumber);
925 my $data = $sth->fetchall_arrayref({});
927 return ( scalar(@$data), $data );
930 =head2 UpdateGuarantees
932 &UpdateGuarantees($parent_borrno);
935 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
936 with the modified information
941 sub UpdateGuarantees {
943 my $dbh = C4::Context->dbh;
944 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
945 for ( my $i = 0 ; $i < $count ; $i++ ) {
948 # It looks like the $i is only being returned to handle walking through
949 # the array, which is probably better done as a foreach loop.
951 my $guaquery = qq|UPDATE borrowers
952 SET address='$data{'address'}',fax='$data{'fax'}',
953 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
954 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
956 my $sth3 = $dbh->prepare($guaquery);
961 =head2 GetPendingIssues
963 ($count, $issues) = &GetPendingIssues($borrowernumber);
965 Looks up what the patron with the given borrowernumber has borrowed.
967 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
968 reference-to-array, where each element is a reference-to-hash; the
969 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
970 in the Koha database. C<$count> is the number of elements in
976 sub GetPendingIssues {
977 my ($borrowernumber) = @_;
978 my $dbh = C4::Context->dbh;
980 my $sth = $dbh->prepare(
981 "SELECT * FROM issues
982 LEFT JOIN items ON issues.itemnumber=items.itemnumber
983 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
984 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
987 AND returndate IS NULL
988 ORDER BY issues.issuedate"
990 $sth->execute($borrowernumber);
991 my $data = $sth->fetchall_arrayref({});
992 my $today = POSIX::strftime("%Y%m%d", localtime);
994 my $datedue = $_->{'date_due'};
996 if ( $datedue < $today ) {
1001 return ( scalar(@$data), $data );
1006 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1008 Looks up what the patron with the given borrowernumber has borrowed,
1009 and sorts the results.
1011 C<$sortkey> is the name of a field on which to sort the results. This
1012 should be the name of a field in the C<issues>, C<biblio>,
1013 C<biblioitems>, or C<items> table in the Koha database.
1015 C<$limit> is the maximum number of results to return.
1017 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1018 reference-to-array, where each element is a reference-to-hash; the
1019 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1020 C<items> tables of the Koha database. C<$count> is the number of
1021 elements in C<$issues>
1027 my ( $borrowernumber, $order, $limit ) = @_;
1029 #FIXME: sanity-check order and limit
1030 my $dbh = C4::Context->dbh;
1033 "Select *,items.timestamp AS itemstimestamp from
1035 LEFT JOIN items on items.itemnumber=issues.itemnumber
1036 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1037 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1038 where borrowernumber=?
1040 if ( $limit != 0 ) {
1041 $query .= " limit $limit";
1045 my $sth = $dbh->prepare($query);
1046 $sth->execute($borrowernumber);
1049 while ( my $data = $sth->fetchrow_hashref ) {
1050 $result[$i] = $data;
1055 # get all issued items for borrowernumber from oldissues table
1056 # large chunk of older issues data put into table oldissues
1057 # to speed up db calls for issuing items
1058 if ( C4::Context->preference("ReadingHistory") ) {
1059 my $query2 = "SELECT * FROM oldissues
1060 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1061 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1062 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1063 WHERE borrowernumber=?
1065 if ( $limit != 0 ) {
1066 $limit = $limit - $count;
1067 $query2 .= " limit $limit";
1070 my $sth2 = $dbh->prepare($query2);
1071 $sth2->execute($borrowernumber);
1073 while ( my $data2 = $sth2->fetchrow_hashref ) {
1074 $result[$i] = $data2;
1081 return ( $i, \@result );
1085 =head2 GetMemberAccountRecords
1087 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1089 Looks up accounting data for the patron with the given borrowernumber.
1091 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1092 reference-to-array, where each element is a reference-to-hash; the
1093 keys are the fields of the C<accountlines> table in the Koha database.
1094 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1095 total amount outstanding for all of the account lines.
1100 sub GetMemberAccountRecords {
1101 my ($borrowernumber,$date) = @_;
1102 my $dbh = C4::Context->dbh;
1108 WHERE borrowernumber=?);
1109 my @bind = ($borrowernumber);
1110 if ($date && $date ne ''){
1111 $strsth.=" AND date < ? ";
1114 $strsth.=" ORDER BY date desc,timestamp DESC";
1115 my $sth= $dbh->prepare( $strsth );
1116 $sth->execute( @bind );
1118 while ( my $data = $sth->fetchrow_hashref ) {
1119 $acctlines[$numlines] = $data;
1121 $total += $data->{'amountoutstanding'};
1124 return ( $total, \@acctlines,$numlines);
1127 =head2 GetBorNotifyAcctRecord
1129 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1131 Looks up accounting data for the patron with the given borrowernumber per file number.
1133 (FIXME - I'm not at all sure what this is about.)
1135 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1136 reference-to-array, where each element is a reference-to-hash; the
1137 keys are the fields of the C<accountlines> table in the Koha database.
1138 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1139 total amount outstanding for all of the account lines.
1143 sub GetBorNotifyAcctRecord {
1144 my ( $borrowernumber, $notifyid ) = @_;
1145 my $dbh = C4::Context->dbh;
1148 my $sth = $dbh->prepare(
1151 WHERE borrowernumber=?
1153 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')
1154 AND amountoutstanding != '0'
1155 ORDER BY notify_id,accounttype
1157 $sth->execute( $borrowernumber, $notifyid );
1159 while ( my $data = $sth->fetchrow_hashref ) {
1160 $acctlines[$numlines] = $data;
1162 $total += $data->{'amountoutstanding'};
1165 return ( $total, \@acctlines, $numlines );
1168 =head2 checkuniquemember (OUEST-PROVENCE)
1170 $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1172 Checks that a member exists or not in the database.
1174 C<&result> is 1 (=exist) or 0 (=does not exist)
1175 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1176 C<&surname> is the surname
1177 C<&categorycode> is from categorycode table
1178 C<&firstname> is the firstname (only if collectivity=0)
1179 C<&dateofbirth> is the date of birth (only if collectivity=0)
1183 sub checkuniquemember {
1184 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1185 my $dbh = C4::Context->dbh;
1187 if ($collectivity) {
1189 # $request="select count(*) from borrowers where surname=? and categorycode=?";
1191 "select borrowernumber,categorycode from borrowers where surname=? ";
1195 # $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1197 "select borrowernumber,categorycode from borrowers where surname=? and firstname=? and dateofbirth=?";
1199 my $sth = $dbh->prepare($request);
1200 if ($collectivity) {
1201 $sth->execute( uc($surname) );
1204 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1206 my @data = $sth->fetchrow;
1209 return $data[0], $data[1];
1219 sub checkcardnumber {
1220 my ($cardnumber,$borrowernumber) = @_;
1221 my $dbh = C4::Context->dbh;
1222 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1223 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1224 my $sth = $dbh->prepare($query);
1225 if ($borrowernumber) {
1226 $sth->execute($cardnumber,$borrowernumber);
1228 $sth->execute($cardnumber);
1230 if (my $data= $sth->fetchrow_hashref()){
1240 =head2 getzipnamecity (OUEST-PROVENCE)
1242 take all info from table city for the fields city and zip
1243 check for the name and the zip code of the city selected
1247 sub getzipnamecity {
1249 my $dbh = C4::Context->dbh;
1252 "select city_name,city_zipcode from cities where cityid=? ");
1253 $sth->execute($cityid);
1254 my @data = $sth->fetchrow;
1255 return $data[0], $data[1];
1259 =head2 getdcity (OUEST-PROVENCE)
1261 recover cityid with city_name condition
1266 my ($city_name) = @_;
1267 my $dbh = C4::Context->dbh;
1268 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1269 $sth->execute($city_name);
1270 my $data = $sth->fetchrow;
1275 =head2 GetExpiryDate
1277 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1278 process expiry date given a date and a categorycode
1282 my ( $categorycode, $dateenrolled ) = @_;
1283 my $dbh = C4::Context->dbh;
1286 "select enrolmentperiod from categories where categorycode=?");
1287 $sth->execute($categorycode);
1288 my ($enrolmentperiod) = $sth->fetchrow;
1289 $enrolmentperiod = 12 unless ($enrolmentperiod);
1290 my @date=split /-/,format_date_in_iso($dateenrolled);
1291 @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1292 return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1295 =head2 checkuserpassword (OUEST-PROVENCE)
1297 check for the password and login are not used
1298 return the number of record
1299 0=> NOT USED 1=> USED
1303 sub checkuserpassword {
1304 my ( $borrowernumber, $userid, $password ) = @_;
1305 $password = md5_base64($password);
1306 my $dbh = C4::Context->dbh;
1309 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1311 $sth->execute( $borrowernumber, $userid, $password );
1312 my $number_rows = $sth->fetchrow;
1313 return $number_rows;
1317 =head2 GetborCatFromCatType
1319 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1321 Looks up the different types of borrowers in the database. Returns two
1322 elements: a reference-to-array, which lists the borrower category
1323 codes, and a reference-to-hash, which maps the borrower category codes
1324 to category descriptions.
1329 sub GetborCatFromCatType {
1330 my ( $category_type, $action ) = @_;
1331 my $dbh = C4::Context->dbh;
1332 my $request = qq| SELECT categorycode,description
1335 ORDER BY categorycode|;
1336 my $sth = $dbh->prepare($request);
1338 $sth->execute($category_type);
1347 while ( my $data = $sth->fetchrow_hashref ) {
1348 push @codes, $data->{'categorycode'};
1349 $labels{ $data->{'categorycode'} } = $data->{'description'};
1352 return ( \@codes, \%labels );
1355 =head2 GetBorrowercategory
1357 $hashref = &GetBorrowercategory($categorycode);
1359 Given the borrower's category code, the function returns the corresponding
1360 data hashref for a comprehensive information display.
1364 sub GetBorrowercategory {
1366 my $dbh = C4::Context->dbh;
1369 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1371 WHERE categorycode = ?"
1373 $sth->execute($catcode);
1375 $sth->fetchrow_hashref;
1378 } # sub getborrowercategory
1380 =head2 ethnicitycategories
1382 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1384 Looks up the different ethnic types in the database. Returns two
1385 elements: a reference-to-array, which lists the ethnicity codes, and a
1386 reference-to-hash, which maps the ethnicity codes to ethnicity
1393 sub ethnicitycategories {
1394 my $dbh = C4::Context->dbh;
1395 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1399 while ( my $data = $sth->fetchrow_hashref ) {
1400 push @codes, $data->{'code'};
1401 $labels{ $data->{'code'} } = $data->{'name'};
1404 return ( \@codes, \%labels );
1409 $ethn_name = &fixEthnicity($ethn_code);
1411 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1412 corresponding descriptive name from the C<ethnicity> table in the
1413 Koha database ("European" or "Pacific Islander").
1420 my $ethnicity = shift;
1421 return unless $ethnicity;
1422 my $dbh = C4::Context->dbh;
1423 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1424 $sth->execute($ethnicity);
1425 my $data = $sth->fetchrow_hashref;
1427 return $data->{'name'};
1428 } # sub fixEthnicity
1432 $dateofbirth,$date = &GetAge($date);
1434 this function return the borrowers age with the value of dateofbirth
1440 my ( $date, $date_ref ) = @_;
1442 if ( not defined $date_ref ) {
1443 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1446 my ( $year1, $month1, $day1 ) = split /-/, $date;
1447 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1449 my $age = $year2 - $year1;
1450 if ( $month1 . $day1 > $month2 . $day2 ) {
1457 =head2 get_institutions
1458 $insitutions = get_institutions();
1460 Just returns a list of all the borrowers of type I, borrownumber and name
1465 sub get_institutions {
1466 my $dbh = C4::Context->dbh();
1469 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1473 while ( my $data = $sth->fetchrow_hashref() ) {
1474 $orgs{ $data->{'borrowernumber'} } = $data;
1479 } # sub get_institutions
1481 =head2 add_member_orgs
1483 add_member_orgs($borrowernumber,$borrowernumbers);
1485 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1490 sub add_member_orgs {
1491 my ( $borrowernumber, $otherborrowers ) = @_;
1492 my $dbh = C4::Context->dbh();
1494 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1495 my $sth = $dbh->prepare($query);
1496 foreach my $otherborrowernumber (@$otherborrowers) {
1497 $sth->execute( $borrowernumber, $otherborrowernumber );
1501 } # sub add_member_orgs
1503 =head2 GetCities (OUEST-PROVENCE)
1505 ($id_cityarrayref, $city_hashref) = &GetCities();
1507 Looks up the different city and zip in the database. Returns two
1508 elements: a reference-to-array, which lists the zip city
1509 codes, and a reference-to-hash, which maps the name of the city.
1510 WHERE =>OUEST PROVENCE OR EXTERIEUR
1516 #my ($type_city) = @_;
1517 my $dbh = C4::Context->dbh;
1518 my $query = qq|SELECT cityid,city_name
1520 ORDER BY city_name|;
1521 my $sth = $dbh->prepare($query);
1523 #$sth->execute($type_city);
1528 # insert empty value to create a empty choice in cgi popup
1530 while ( my $data = $sth->fetchrow_hashref ) {
1532 push @id, $data->{'cityid'};
1533 $city{ $data->{'cityid'} } = $data->{'city_name'};
1536 #test to know if the table contain some records if no the function return nothing
1544 return ( \@id, \%city );
1548 =head2 GetSortDetails (OUEST-PROVENCE)
1550 ($lib) = &GetSortDetails($category,$sortvalue);
1552 Returns the authorized value details
1553 C<&$lib>return value of authorized value details
1554 C<&$sortvalue>this is the value of authorized value
1555 C<&$category>this is the value of authorized value category
1559 sub GetSortDetails {
1560 my ( $category, $sortvalue ) = @_;
1561 my $dbh = C4::Context->dbh;
1562 my $query = qq|SELECT lib
1563 FROM authorised_values
1565 AND authorised_value=? |;
1566 my $sth = $dbh->prepare($query);
1567 $sth->execute( $category, $sortvalue );
1568 my $lib = $sth->fetchrow;
1572 =head2 DeleteBorrower
1574 () = &DeleteBorrower($member);
1576 delete all data fo borrowers and add record to deletedborrowers table
1577 C<&$member>this is the borrowernumber
1581 sub MoveMemberToDeleted {
1583 my $dbh = C4::Context->dbh;
1585 $query = qq|SELECT *
1587 WHERE borrowernumber=?|;
1588 my $sth = $dbh->prepare($query);
1589 $sth->execute($member);
1590 my @data = $sth->fetchrow_array;
1593 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1594 . ( "?," x ( scalar(@data) - 1 ) )
1596 $sth->execute(@data);
1602 DelMember($borrowernumber);
1604 This function remove directly a borrower whitout writing it on deleteborrower.
1605 + Deletes reserves for the borrower
1610 my $dbh = C4::Context->dbh;
1611 my $borrowernumber = shift;
1612 warn "in delmember with $borrowernumber";
1613 return unless $borrowernumber; # borrowernumber is mandatory.
1615 my $query = qq|DELETE
1617 WHERE borrowernumber=?|;
1618 my $sth = $dbh->prepare($query);
1619 $sth->execute($borrowernumber);
1624 WHERE borrowernumber = ?
1626 $sth = $dbh->prepare($query);
1627 $sth->execute($borrowernumber);
1629 &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"")
1630 if C4::Context->preference("BorrowersLog");
1634 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1636 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1637 Extending the subscription to a given date or to the expiry date calculated on local date.
1641 sub ExtendMemberSubscriptionTo {
1642 my ( $borrowerid,$date) = @_;
1643 my $dbh = C4::Context->dbh;
1645 $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1646 my $borrower = GetMember($borrowerid,'borrowernumber');
1647 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1649 my $sth = $dbh->do(<<EOF);
1651 SET dateexpiry='$date'
1652 WHERE borrowernumber='$borrowerid'
1654 return $date if ($sth);
1658 =head2 GetRoadTypes (OUEST-PROVENCE)
1660 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1662 Looks up the different road type . Returns two
1663 elements: a reference-to-array, which lists the id_roadtype
1664 codes, and a reference-to-hash, which maps the road type of the road .
1670 my $dbh = C4::Context->dbh;
1672 SELECT roadtypeid,road_type
1674 ORDER BY road_type|;
1675 my $sth = $dbh->prepare($query);
1680 # insert empty value to create a empty choice in cgi popup
1682 while ( my $data = $sth->fetchrow_hashref ) {
1684 push @id, $data->{'roadtypeid'};
1685 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1688 #test to know if the table contain some records if no the function return nothing
1696 return ( \@id, \%roadtype );
1702 =head2 GetTitles (OUEST-PROVENCE)
1704 ($borrowertitle)= &GetTitles();
1706 Looks up the different title . Returns array with all borrowers title
1711 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1712 unshift( @borrowerTitle, "" );
1713 return ( \@borrowerTitle);
1718 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1720 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1722 Returns the description of roadtype
1723 C<&$roadtype>return description of road type
1724 C<&$roadtypeid>this is the value of roadtype s
1728 sub GetRoadTypeDetails {
1729 my ($roadtypeid) = @_;
1730 my $dbh = C4::Context->dbh;
1734 WHERE roadtypeid=?|;
1735 my $sth = $dbh->prepare($query);
1736 $sth->execute($roadtypeid);
1737 my $roadtype = $sth->fetchrow;
1741 =head2 GetBorrowersWhoHaveNotBorrowedSince
1743 &GetBorrowersWhoHaveNotBorrowedSince($date)
1745 this function get all borrowers who haven't borrowed since the date given on input arg.
1749 sub GetBorrowersWhoHaveNotBorrowedSince {
1751 return unless $date; # date is mandatory.
1752 my $dbh = C4::Context->dbh;
1754 SELECT borrowers.borrowernumber,max(timestamp)
1756 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1757 WHERE issues.borrowernumber IS NOT NULL
1758 GROUP BY borrowers.borrowernumber
1760 my $sth = $dbh->prepare($query);
1764 while ( my $data = $sth->fetchrow_hashref ) {
1765 push @results, $data;
1770 =head2 GetBorrowersWhoHaveNeverBorrowed
1772 $results = &GetBorrowersWhoHaveNeverBorrowed
1774 this function get all borrowers who have never borrowed.
1776 I<$result> is a ref to an array which all elements are a hasref.
1780 sub GetBorrowersWhoHaveNeverBorrowed {
1781 my $dbh = C4::Context->dbh;
1783 SELECT borrowers.borrowernumber,max(timestamp)
1785 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1786 WHERE issues.borrowernumber IS NULL
1788 my $sth = $dbh->prepare($query);
1791 while ( my $data = $sth->fetchrow_hashref ) {
1792 push @results, $data;
1797 =head2 GetBorrowersWithIssuesHistoryOlderThan
1799 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1801 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1803 I<$result> is a ref to an array which all elements are a hashref.
1804 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1808 sub GetBorrowersWithIssuesHistoryOlderThan {
1809 my $dbh = C4::Context->dbh;
1811 return unless $date; # date is mandatory.
1813 SELECT count(borrowernumber) as n,borrowernumber
1815 WHERE returndate < ?
1816 AND borrowernumber IS NOT NULL
1817 GROUP BY borrowernumber
1819 my $sth = $dbh->prepare($query);
1820 $sth->execute($date);
1823 while ( my $data = $sth->fetchrow_hashref ) {
1824 push @results, $data;
1829 END { } # module clean-up code here (global destructor)