3 # Copyright 2000-2003 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
31 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
35 $debug = $ENV{DEBUG} || 0;
46 &GetMemberIssuesAndFines
65 &GetMemberAccountRecords
66 &GetBorNotifyAcctRecord
71 &GetBorrowersWhoHaveNotBorrowedSince
72 &GetBorrowersWhoHaveNeverBorrowed
73 &GetBorrowersWithIssuesHistoryOlderThan
94 &ExtendMemberSubscriptionTo
111 C4::Members - Perl Module containing convenience functions for member handling
119 This module contains routines for adding, modifying and deleting members/patrons/borrowers
127 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
129 Looks up patrons (borrowers) by name.
131 BUGFIX 499: C<$type> is now used to determine type of search.
132 if $type is "simple", search is performed on the first letter of the
135 $category_type is used to get a specified type of user.
136 (mainly adults when creating a child.)
138 C<$searchstring> is a space-separated list of search terms. Each term
139 must match the beginning a borrower's surname, first name, or other
142 C<$filter> is assumed to be a list of elements to filter results on
144 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
146 C<&SearchMember> returns a two-element list. C<$borrowers> is a
147 reference-to-array; each element is a reference-to-hash, whose keys
148 are the fields of the C<borrowers> table in the Koha database.
149 C<$count> is the number of elements in C<$borrowers>.
154 #used by member enquiries from the intranet
155 #called by member.pl and circ/circulation.pl
157 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
158 my $dbh = C4::Context->dbh;
164 # this is used by circulation everytime a new borrowers cardnumber is scanned
165 # so we can check an exact match first, if that works return, otherwise do the rest
166 $query = "SELECT * FROM borrowers
167 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
169 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
170 $sth->execute($searchstring);
171 my $data = $sth->fetchall_arrayref({});
173 return ( scalar(@$data), $data );
177 if ( $type eq "simple" ) # simple search for one letter only
179 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
180 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
181 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
182 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
183 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
186 $query.=" ORDER BY $orderby";
187 @bind = ("$searchstring%","$searchstring");
189 else # advanced search looking in surname, firstname and othernames
191 @data = split( ' ', $searchstring );
194 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
195 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
196 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
199 $query.="((surname LIKE ? OR surname LIKE ?
200 OR firstname LIKE ? OR firstname LIKE ?
201 OR othernames LIKE ? OR othernames LIKE ?)
203 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
205 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
206 "$data[0]%", "% $data[0]%"
208 for ( my $i = 1 ; $i < $count ; $i++ ) {
209 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
210 OR firstname LIKE ? OR firstname LIKE ?
211 OR othernames LIKE ? OR othernames LIKE ?)";
213 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
214 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
218 $query = $query . ") OR cardnumber LIKE ? ";
219 push( @bind, $searchstring );
220 if (C4::Context->preference('ExtendedPatronAttributes')) {
221 $query .= "OR borrowernumber IN (
222 SELECT borrowernumber
223 FROM borrower_attributes
224 JOIN borrower_attribute_types USING (code)
225 WHERE staff_searchable = 1
228 push (@bind, $searchstring);
230 $query .= "order by $orderby";
235 $sth = $dbh->prepare($query);
237 $debug and print STDERR "Q $orderby : $query\n";
238 $sth->execute(@bind);
240 $data = $sth->fetchall_arrayref({});
243 return ( scalar(@$data), $data );
246 =head2 GetMemberDetails
248 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
250 Looks up a patron and returns information about him or her. If
251 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
252 up the borrower by number; otherwise, it looks up the borrower by card
255 C<$borrower> is a reference-to-hash whose keys are the fields of the
256 borrowers table in the Koha database. In addition,
257 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
258 about the patron. Its keys act as flags :
260 if $borrower->{flags}->{LOST} {
261 # Patron's card was reported lost
264 Each flag has a C<message> key, giving a human-readable explanation of
265 the flag. If the state of a flag means that the patron should not be
266 allowed to borrow any more books, then it will have a C<noissues> key
269 The possible flags are:
275 =item Shows the patron's credit or debt, if any.
283 =item (Gone, no address.) Set if the patron has left without giving a
292 =item Set if the patron's card has been reported as lost.
300 =item Set if the patron has been debarred.
308 =item Any additional notes about the patron.
316 =item Set if the patron has overdue items. This flag has several keys:
318 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
319 overdue items. Its elements are references-to-hash, each describing an
320 overdue item. The keys are selected fields from the issues, biblio,
321 biblioitems, and items tables of the Koha database.
323 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
324 the overdue items, one per line.
332 =item Set if any items that the patron has reserved are available.
334 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
335 available items. Each element is a reference-to-hash whose keys are
336 fields from the reserves table of the Koha database.
342 sub GetMemberDetails {
343 my ( $borrowernumber, $cardnumber ) = @_;
344 my $dbh = C4::Context->dbh;
347 if ($borrowernumber) {
348 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
349 $sth->execute($borrowernumber);
351 elsif ($cardnumber) {
352 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
353 $sth->execute($cardnumber);
358 my $borrower = $sth->fetchrow_hashref;
359 my ($amount) = GetMemberAccountRecords( $borrowernumber);
360 $borrower->{'amountoutstanding'} = $amount;
361 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
362 my $flags = patronflags( $borrower);
365 $sth = $dbh->prepare("select bit,flag from userflags");
367 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
368 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
369 $accessflagshash->{$flag} = 1;
373 $borrower->{'flags'} = $flags;
374 $borrower->{'authflags'} = $accessflagshash;
376 # find out how long the membership lasts
379 "select enrolmentperiod from categories where categorycode = ?");
380 $sth->execute( $borrower->{'categorycode'} );
381 my $enrolment = $sth->fetchrow;
382 $borrower->{'enrolmentperiod'} = $enrolment;
383 return ($borrower); #, $flags, $accessflagshash);
390 NOTE!: If you change this function, be sure to update the POD for
393 $flags = &patronflags($patron);
396 {message} Message showing patron's credit or debt
397 {noissues} Set if patron owes >$5.00
398 {GNA} Set if patron gone w/o address
399 {message} "Borrower has no valid address"
401 {LOST} Set if patron's card reported lost
402 {message} Message to this effect
404 {DBARRED} Set is patron is debarred
405 {message} Message to this effect
407 {NOTES} Set if patron has notes
408 {message} Notes about patron
409 {ODUES} Set if patron has overdue books
411 {itemlist} ref-to-array: list of overdue books
412 {itemlisttext} Text list of overdue items
413 {WAITING} Set if there are items available that the
415 {message} Message to this effect
416 {itemlist} ref-to-array: list of available items
419 # FIXME rename this function.
422 my ( $patroninformation) = @_;
423 my $dbh=C4::Context->dbh;
424 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
427 my $noissuescharge = C4::Context->preference("noissuescharge");
428 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
429 $flaginfo{'amount'} = sprintf "%.02f",$amount;
430 if ( $amount > $noissuescharge ) {
431 $flaginfo{'noissues'} = 1;
433 $flags{'CHARGES'} = \%flaginfo;
435 elsif ( $amount < 0 ) {
437 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
438 $flags{'CREDITS'} = \%flaginfo;
440 if ( $patroninformation->{'gonenoaddress'}
441 && $patroninformation->{'gonenoaddress'} == 1 )
444 $flaginfo{'message'} = 'Borrower has no valid address.';
445 $flaginfo{'noissues'} = 1;
446 $flags{'GNA'} = \%flaginfo;
448 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
450 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
451 $flaginfo{'noissues'} = 1;
452 $flags{'LOST'} = \%flaginfo;
454 if ( $patroninformation->{'debarred'}
455 && $patroninformation->{'debarred'} == 1 )
458 $flaginfo{'message'} = 'Borrower is Debarred.';
459 $flaginfo{'noissues'} = 1;
460 $flags{'DBARRED'} = \%flaginfo;
462 if ( $patroninformation->{'borrowernotes'}
463 && $patroninformation->{'borrowernotes'} )
466 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
467 $flags{'NOTES'} = \%flaginfo;
469 my ( $odues, $itemsoverdue ) =
470 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
473 $flaginfo{'message'} = "Yes";
474 $flaginfo{'itemlist'} = $itemsoverdue;
475 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
478 $flaginfo{'itemlisttext'} .=
479 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
481 $flags{'ODUES'} = \%flaginfo;
483 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
484 my $nowaiting = scalar @itemswaiting;
485 if ( $nowaiting > 0 ) {
487 $flaginfo{'message'} = "Reserved items available";
488 $flaginfo{'itemlist'} = \@itemswaiting;
489 $flags{'WAITING'} = \%flaginfo;
497 $borrower = &GetMember($information, $type);
499 Looks up information about a patron (borrower) by either card number
500 ,firstname, or borrower number, depending on $type value.
501 If C<$type> == 'cardnumber', C<&GetBorrower>
502 searches by cardnumber then by firstname if not found in cardnumber;
503 otherwise, it searches by borrowernumber.
505 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
506 the C<borrowers> table in the Koha database.
512 my ( $information, $type ) = @_;
513 my $dbh = C4::Context->dbh;
516 SELECT borrowers.*, categories.category_type, categories.description
518 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
520 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
521 $information = uc $information;
522 $sth = $dbh->prepare("$select WHERE $type=?");
524 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
526 $sth->execute($information);
527 my $data = $sth->fetchrow_hashref;
529 ($data) and return ($data);
531 if ($type eq 'cardnumber' || $type eq 'firstname') { # otherwise, try with firstname
532 $sth = $dbh->prepare("$select WHERE firstname like ?");
533 $sth->execute($information);
534 $data = $sth->fetchrow_hashref;
536 ($data) and return ($data);
541 =item GetMemberIssuesAndFines
543 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
545 Returns aggregate data about items borrowed by the patron with the
546 given borrowernumber.
548 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
549 number of overdue items the patron currently has borrowed. C<$issue_count> is the
550 number of books the patron currently has borrowed. C<$total_fines> is
551 the total fine currently due by the borrower.
556 sub GetMemberIssuesAndFines {
557 my ( $borrowernumber ) = @_;
558 my $dbh = C4::Context->dbh;
559 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
561 $debug and warn $query."\n";
562 my $sth = $dbh->prepare($query);
563 $sth->execute($borrowernumber);
564 my $issue_count = $sth->fetchrow_arrayref->[0];
567 $sth = $dbh->prepare(
568 "SELECT COUNT(*) FROM issues
569 WHERE borrowernumber = ?
570 AND date_due < now()"
572 $sth->execute($borrowernumber);
573 my $overdue_count = $sth->fetchrow_arrayref->[0];
576 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
577 $sth->execute($borrowernumber);
578 my $total_fines = $sth->fetchrow_arrayref->[0];
581 return ($overdue_count, $issue_count, $total_fines);
588 &ModMember($borrowernumber);
590 Modify borrower's data. All date fields should ALREADY be in ISO format.
597 my $dbh = C4::Context->dbh;
598 my $iso_re = C4::Dates->new()->regexp('iso');
599 foreach (qw(dateofbirth dateexpiry dateenrolled)) {
600 if (my $tempdate = $data{$_}) { # assignment, not comparison
601 ($tempdate =~ /$iso_re/) and next; # Congatulations, you sent a valid ISO date.
602 warn "ModMember given $_ not in ISO format ($tempdate)";
603 if (my $tempdate2 = format_date_in_iso($tempdate)) { # assignment, not comparison
604 $data{$_} = $tempdate2;
606 warn "ModMember cannot convert '$tempdate' (from syspref)";
610 if (!$data{'dateofbirth'}){
611 undef $data{'dateofbirth'};
613 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
615 my %hashborrowerfields;
616 while (my ($field)=$qborrower->fetchrow){
617 $hashborrowerfields{$field}=1;
619 my $query = "UPDATE borrowers SET \n";
623 # test to know if you must update or not the borrower password
624 if ( $data{'password'} eq '****' ) {
625 delete $data{'password'};
627 $data{'password'} = md5_base64( $data{'password'} ) if ($data{'password'} ne "");
628 delete $data{'password'} if ($data{password} eq "");
631 { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
632 $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
633 $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
634 $sth = $dbh->prepare($query);
635 $sth->execute($data{'borrowernumber'});
638 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
639 # so when we update information for an adult we should check for guarantees and update the relevant part
640 # of their records, ie addresses and phone numbers
641 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
642 if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
643 # is adult check guarantees;
644 UpdateGuarantees(%data);
646 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})")
647 if C4::Context->preference("BorrowersLog");
655 $borrowernumber = &AddMember(%borrower);
657 insert new borrower into table
658 Returns the borrowernumber
665 my $dbh = C4::Context->dbh;
666 $data{'userid'} = '' unless $data{'password'};
667 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
669 # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
670 # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
671 # $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
672 # $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
673 # $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
674 # This query should be rewritten to use "?" at execute.
675 if (!$data{'dateofbirth'}){
676 undef ($data{'dateofbirth'});
679 "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
680 . ",surname=" . $dbh->quote( $data{'surname'} )
681 . ",firstname=" . $dbh->quote( $data{'firstname'} )
682 . ",title=" . $dbh->quote( $data{'title'} )
683 . ",othernames=" . $dbh->quote( $data{'othernames'} )
684 . ",initials=" . $dbh->quote( $data{'initials'} )
685 . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
686 . ",streettype=" . $dbh->quote( $data{'streettype'} )
687 . ",address=" . $dbh->quote( $data{'address'} )
688 . ",address2=" . $dbh->quote( $data{'address2'} )
689 . ",zipcode=" . $dbh->quote( $data{'zipcode'} )
690 . ",city=" . $dbh->quote( $data{'city'} )
691 . ",phone=" . $dbh->quote( $data{'phone'} )
692 . ",email=" . $dbh->quote( $data{'email'} )
693 . ",mobile=" . $dbh->quote( $data{'mobile'} )
694 . ",phonepro=" . $dbh->quote( $data{'phonepro'} )
695 . ",opacnote=" . $dbh->quote( $data{'opacnote'} )
696 . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
697 . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
698 . ",branchcode=" . $dbh->quote( $data{'branchcode'} )
699 . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
700 . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
701 . ",contactname=" . $dbh->quote( $data{'contactname'} )
702 . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
703 . ",dateexpiry=" . $dbh->quote( $data{'dateexpiry'} )
704 . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
705 . ",B_address=" . $dbh->quote( $data{'B_address'} )
706 . ",B_zipcode=" . $dbh->quote( $data{'B_zipcode'} )
707 . ",B_city=" . $dbh->quote( $data{'B_city'} )
708 . ",B_phone=" . $dbh->quote( $data{'B_phone'} )
709 . ",B_email=" . $dbh->quote( $data{'B_email'} )
710 . ",password=" . $dbh->quote( $data{'password'} )
711 . ",userid=" . $dbh->quote( $data{'userid'} )
712 . ",sort1=" . $dbh->quote( $data{'sort1'} )
713 . ",sort2=" . $dbh->quote( $data{'sort2'} )
714 . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
715 . ",emailpro=" . $dbh->quote( $data{'emailpro'} )
716 . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
717 . ",sex=" . $dbh->quote( $data{'sex'} )
718 . ",fax=" . $dbh->quote( $data{'fax'} )
719 . ",relationship=" . $dbh->quote( $data{'relationship'} )
720 . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
721 . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
722 . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
723 . ",lost=" . $dbh->quote( $data{'lost'} )
724 . ",debarred=" . $dbh->quote( $data{'debarred'} )
725 . ",ethnicity=" . $dbh->quote( $data{'ethnicity'} )
726 . ",ethnotes=" . $dbh->quote( $data{'ethnotes'} )
727 . ",altcontactsurname=" . $dbh->quote( $data{'altcontactsurname'} )
728 . ",altcontactfirstname=" . $dbh->quote( $data{'altcontactfirstname'} )
729 . ",altcontactaddress1=" . $dbh->quote( $data{'altcontactaddress1'} )
730 . ",altcontactaddress2=" . $dbh->quote( $data{'altcontactaddress2'} )
731 . ",altcontactaddress3=" . $dbh->quote( $data{'altcontactaddress3'} )
732 . ",altcontactzipcode=" . $dbh->quote( $data{'altcontactzipcode'} )
733 . ",altcontactphone=" . $dbh->quote( $data{'altcontactphone'} ) ;
734 $debug and print STDERR "AddMember SQL: ($query)\n";
735 my $sth = $dbh->prepare($query);
736 # print "Executing SQL: $query\n";
739 $data{'borrowernumber'} = $dbh->{'mysql_insertid'}; # unneeded w/ autoincrement ?
740 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
742 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
744 # check for enrollment fee & add it if needed
745 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
746 $sth->execute($data{'categorycode'});
747 my ($enrolmentfee) = $sth->fetchrow;
749 # insert fee in patron debts
750 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
752 return $data{'borrowernumber'};
756 my ($uid,$member) = @_;
757 my $dbh = C4::Context->dbh;
758 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
759 # Then we need to tell the user and have them create a new one.
762 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
763 $sth->execute( $uid, $member );
764 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
774 my ( $uid, $member, $digest ) = @_;
775 my $dbh = C4::Context->dbh;
777 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
778 #Then we need to tell the user and have them create a new one.
782 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
783 $sth->execute( $uid, $member );
784 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
788 #Everything is good so we can update the information.
791 "update borrowers set userid=?, password=? where borrowernumber=?");
792 $sth->execute( $uid, $digest, $member );
796 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
802 =item fixup_cardnumber
804 Warning: The caller is responsible for locking the members table in write
805 mode, to avoid database corruption.
809 use vars qw( @weightings );
810 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
812 sub fixup_cardnumber ($) {
813 my ($cardnumber) = @_;
814 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
815 $autonumber_members = 0 unless defined $autonumber_members;
817 # Find out whether member numbers should be generated
818 # automatically. Should be either "1" or something else.
819 # Defaults to "0", which is interpreted as "no".
821 # if ($cardnumber !~ /\S/ && $autonumber_members) {
822 if ($autonumber_members) {
823 my $dbh = C4::Context->dbh;
824 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
826 # if checkdigit is selected, calculate katipo-style cardnumber.
827 # otherwise, just use the max()
828 # purpose: generate checksum'd member numbers.
829 # We'll assume we just got the max value of digits 2-8 of member #'s
830 # from the database and our job is to increment that by one,
831 # determine the 1st and 9th digits and return the full string.
834 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
838 my $data = $sth->fetchrow_hashref;
839 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
841 if ( !$cardnumber ) { # If DB has no values,
842 $cardnumber = 1000000; # start at 1000000
849 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
851 # read weightings, left to right, 1 char at a time
852 my $temp1 = $weightings[$i];
854 # sequence left to right, 1 char at a time
855 my $temp2 = substr( $cardnumber, $i, 1 );
857 # mult each char 1-7 by its corresponding weighting
858 $sum += $temp1 * $temp2;
861 my $rem = ( $sum % 11 );
862 $rem = 'X' if $rem == 10;
864 $cardnumber = "V$cardnumber$rem";
868 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
869 # better. I'll leave the original in in case it needs to be changed for you
872 "select max(cast(cardnumber as signed)) from borrowers");
874 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
878 my ($result) = $sth->fetchrow;
880 $cardnumber = $result + 1;
888 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
889 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
890 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
892 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
893 with children) and looks up the borrowers who are guaranteed by that
894 borrower (i.e., the patron's children).
896 C<&GetGuarantees> returns two values: an integer giving the number of
897 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
898 of references to hash, which gives the actual results.
904 my ($borrowernumber) = @_;
905 my $dbh = C4::Context->dbh;
908 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
910 $sth->execute($borrowernumber);
913 my $data = $sth->fetchall_arrayref({});
915 return ( scalar(@$data), $data );
918 =head2 UpdateGuarantees
920 &UpdateGuarantees($parent_borrno);
923 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
924 with the modified information
929 sub UpdateGuarantees {
931 my $dbh = C4::Context->dbh;
932 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
933 for ( my $i = 0 ; $i < $count ; $i++ ) {
936 # It looks like the $i is only being returned to handle walking through
937 # the array, which is probably better done as a foreach loop.
939 my $guaquery = qq|UPDATE borrowers
940 SET address='$data{'address'}',fax='$data{'fax'}',
941 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
942 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
944 my $sth3 = $dbh->prepare($guaquery);
949 =head2 GetPendingIssues
951 ($count, $issues) = &GetPendingIssues($borrowernumber);
953 Looks up what the patron with the given borrowernumber has borrowed.
955 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
956 reference-to-array, where each element is a reference-to-hash; the
957 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
958 in the Koha database. C<$count> is the number of elements in
964 sub GetPendingIssues {
965 my ($borrowernumber) = @_;
966 my $dbh = C4::Context->dbh;
968 my $sth = $dbh->prepare(
969 "SELECT * FROM issues
970 LEFT JOIN items ON issues.itemnumber=items.itemnumber
971 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
972 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
975 ORDER BY issues.issuedate"
977 $sth->execute($borrowernumber);
978 my $data = $sth->fetchall_arrayref({});
979 my $today = POSIX::strftime("%Y%m%d", localtime);
981 my $datedue = $_->{'date_due'};
983 if ( $datedue < $today ) {
988 return ( scalar(@$data), $data );
993 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
995 Looks up what the patron with the given borrowernumber has borrowed,
996 and sorts the results.
998 C<$sortkey> is the name of a field on which to sort the results. This
999 should be the name of a field in the C<issues>, C<biblio>,
1000 C<biblioitems>, or C<items> table in the Koha database.
1002 C<$limit> is the maximum number of results to return.
1004 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1005 reference-to-array, where each element is a reference-to-hash; the
1006 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1007 C<items> tables of the Koha database. C<$count> is the number of
1008 elements in C<$issues>
1014 my ( $borrowernumber, $order, $limit ) = @_;
1016 #FIXME: sanity-check order and limit
1017 my $dbh = C4::Context->dbh;
1020 "SELECT *,items.timestamp AS itemstimestamp
1022 LEFT JOIN items on items.itemnumber=issues.itemnumber
1023 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1024 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1025 WHERE borrowernumber=?
1027 SELECT *,items.timestamp AS itemstimestamp
1029 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1030 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1031 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1032 WHERE borrowernumber=?
1034 if ( $limit != 0 ) {
1035 $query .= " limit $limit";
1039 my $sth = $dbh->prepare($query);
1040 $sth->execute($borrowernumber, $borrowernumber);
1043 while ( my $data = $sth->fetchrow_hashref ) {
1044 $result[$i] = $data;
1049 # get all issued items for borrowernumber from oldissues table
1050 # large chunk of older issues data put into table oldissues
1051 # to speed up db calls for issuing items
1052 if ( C4::Context->preference("ReadingHistory") ) {
1053 # FIXME oldissues (not to be confused with old_issues) is
1054 # apparently specific to HLT. Not sure if the ReadingHistory
1055 # syspref is still required, as old_issues by design
1056 # is no longer checked with each loan.
1057 my $query2 = "SELECT * FROM oldissues
1058 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1059 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1060 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1061 WHERE borrowernumber=?
1063 if ( $limit != 0 ) {
1064 $limit = $limit - $count;
1065 $query2 .= " limit $limit";
1068 my $sth2 = $dbh->prepare($query2);
1069 $sth2->execute($borrowernumber);
1071 while ( my $data2 = $sth2->fetchrow_hashref ) {
1072 $result[$i] = $data2;
1079 return ( $i, \@result );
1083 =head2 GetMemberAccountRecords
1085 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1087 Looks up accounting data for the patron with the given borrowernumber.
1089 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1090 reference-to-array, where each element is a reference-to-hash; the
1091 keys are the fields of the C<accountlines> table in the Koha database.
1092 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1093 total amount outstanding for all of the account lines.
1098 sub GetMemberAccountRecords {
1099 my ($borrowernumber,$date) = @_;
1100 my $dbh = C4::Context->dbh;
1106 WHERE borrowernumber=?);
1107 my @bind = ($borrowernumber);
1108 if ($date && $date ne ''){
1109 $strsth.=" AND date < ? ";
1112 $strsth.=" ORDER BY date desc,timestamp DESC";
1113 my $sth= $dbh->prepare( $strsth );
1114 $sth->execute( @bind );
1116 while ( my $data = $sth->fetchrow_hashref ) {
1117 $acctlines[$numlines] = $data;
1119 $total += $data->{'amountoutstanding'};
1122 return ( $total, \@acctlines,$numlines);
1125 =head2 GetBorNotifyAcctRecord
1127 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1129 Looks up accounting data for the patron with the given borrowernumber per file number.
1131 (FIXME - I'm not at all sure what this is about.)
1133 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1134 reference-to-array, where each element is a reference-to-hash; the
1135 keys are the fields of the C<accountlines> table in the Koha database.
1136 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1137 total amount outstanding for all of the account lines.
1141 sub GetBorNotifyAcctRecord {
1142 my ( $borrowernumber, $notifyid ) = @_;
1143 my $dbh = C4::Context->dbh;
1146 my $sth = $dbh->prepare(
1149 WHERE borrowernumber=?
1151 AND amountoutstanding != '0'
1152 ORDER BY notify_id,accounttype
1154 # 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')
1156 $sth->execute( $borrowernumber, $notifyid );
1158 while ( my $data = $sth->fetchrow_hashref ) {
1159 $acctlines[$numlines] = $data;
1161 $total += $data->{'amountoutstanding'};
1164 return ( $total, \@acctlines, $numlines );
1167 =head2 checkuniquemember (OUEST-PROVENCE)
1169 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1171 Checks that a member exists or not in the database.
1173 C<&result> is nonzero (=exist) or 0 (=does not exist)
1174 C<&categorycode> is from categorycode table
1175 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1176 C<&surname> is the surname
1177 C<&firstname> is the firstname (only if collectivity=0)
1178 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1182 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1183 # This is especially true since first name is not even a required field.
1185 sub checkuniquemember {
1186 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1187 my $dbh = C4::Context->dbh;
1188 my $request = ($collectivity) ?
1189 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1190 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1191 my $sth = $dbh->prepare($request);
1192 if ($collectivity) {
1193 $sth->execute( uc($surname) );
1195 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1197 my @data = $sth->fetchrow;
1199 ( $data[0] ) and return $data[0], $data[1];
1203 sub checkcardnumber {
1204 my ($cardnumber,$borrowernumber) = @_;
1205 my $dbh = C4::Context->dbh;
1206 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1207 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1208 my $sth = $dbh->prepare($query);
1209 if ($borrowernumber) {
1210 $sth->execute($cardnumber,$borrowernumber);
1212 $sth->execute($cardnumber);
1214 if (my $data= $sth->fetchrow_hashref()){
1224 =head2 getzipnamecity (OUEST-PROVENCE)
1226 take all info from table city for the fields city and zip
1227 check for the name and the zip code of the city selected
1231 sub getzipnamecity {
1233 my $dbh = C4::Context->dbh;
1236 "select city_name,city_zipcode from cities where cityid=? ");
1237 $sth->execute($cityid);
1238 my @data = $sth->fetchrow;
1239 return $data[0], $data[1];
1243 =head2 getdcity (OUEST-PROVENCE)
1245 recover cityid with city_name condition
1250 my ($city_name) = @_;
1251 my $dbh = C4::Context->dbh;
1252 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1253 $sth->execute($city_name);
1254 my $data = $sth->fetchrow;
1259 =head2 GetExpiryDate
1261 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1263 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1264 Return date is also in ISO format.
1269 my ( $categorycode, $dateenrolled ) = @_;
1270 my $enrolmentperiod = 12; # reasonable default
1271 if ($categorycode) {
1272 my $dbh = C4::Context->dbh;
1273 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1274 $sth->execute($categorycode);
1275 $enrolmentperiod = $sth->fetchrow;
1277 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1278 my @date = split /-/,$dateenrolled;
1279 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1282 =head2 checkuserpassword (OUEST-PROVENCE)
1284 check for the password and login are not used
1285 return the number of record
1286 0=> NOT USED 1=> USED
1290 sub checkuserpassword {
1291 my ( $borrowernumber, $userid, $password ) = @_;
1292 $password = md5_base64($password);
1293 my $dbh = C4::Context->dbh;
1296 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1298 $sth->execute( $borrowernumber, $userid, $password );
1299 my $number_rows = $sth->fetchrow;
1300 return $number_rows;
1304 =head2 GetborCatFromCatType
1306 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1308 Looks up the different types of borrowers in the database. Returns two
1309 elements: a reference-to-array, which lists the borrower category
1310 codes, and a reference-to-hash, which maps the borrower category codes
1311 to category descriptions.
1316 sub GetborCatFromCatType {
1317 my ( $category_type, $action ) = @_;
1318 my $dbh = C4::Context->dbh;
1319 my $request = qq| SELECT categorycode,description
1322 ORDER BY categorycode|;
1323 my $sth = $dbh->prepare($request);
1325 $sth->execute($category_type);
1334 while ( my $data = $sth->fetchrow_hashref ) {
1335 push @codes, $data->{'categorycode'};
1336 $labels{ $data->{'categorycode'} } = $data->{'description'};
1339 return ( \@codes, \%labels );
1342 =head2 GetBorrowercategory
1344 $hashref = &GetBorrowercategory($categorycode);
1346 Given the borrower's category code, the function returns the corresponding
1347 data hashref for a comprehensive information display.
1349 $arrayref_hashref = &GetBorrowercategory;
1350 If no category code provided, the function returns all the categories.
1354 sub GetBorrowercategory {
1356 my $dbh = C4::Context->dbh;
1360 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1362 WHERE categorycode = ?"
1364 $sth->execute($catcode);
1366 $sth->fetchrow_hashref;
1374 FROM categories order by description"
1378 $sth->fetchall_arrayref({});
1382 } # sub getborrowercategory
1384 =head2 ethnicitycategories
1386 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1388 Looks up the different ethnic types in the database. Returns two
1389 elements: a reference-to-array, which lists the ethnicity codes, and a
1390 reference-to-hash, which maps the ethnicity codes to ethnicity
1397 sub ethnicitycategories {
1398 my $dbh = C4::Context->dbh;
1399 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1403 while ( my $data = $sth->fetchrow_hashref ) {
1404 push @codes, $data->{'code'};
1405 $labels{ $data->{'code'} } = $data->{'name'};
1408 return ( \@codes, \%labels );
1413 $ethn_name = &fixEthnicity($ethn_code);
1415 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1416 corresponding descriptive name from the C<ethnicity> table in the
1417 Koha database ("European" or "Pacific Islander").
1424 my $ethnicity = shift;
1425 return unless $ethnicity;
1426 my $dbh = C4::Context->dbh;
1427 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1428 $sth->execute($ethnicity);
1429 my $data = $sth->fetchrow_hashref;
1431 return $data->{'name'};
1432 } # sub fixEthnicity
1436 $dateofbirth,$date = &GetAge($date);
1438 this function return the borrowers age with the value of dateofbirth
1444 my ( $date, $date_ref ) = @_;
1446 if ( not defined $date_ref ) {
1447 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1450 my ( $year1, $month1, $day1 ) = split /-/, $date;
1451 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1453 my $age = $year2 - $year1;
1454 if ( $month1 . $day1 > $month2 . $day2 ) {
1461 =head2 get_institutions
1462 $insitutions = get_institutions();
1464 Just returns a list of all the borrowers of type I, borrownumber and name
1469 sub get_institutions {
1470 my $dbh = C4::Context->dbh();
1473 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1477 while ( my $data = $sth->fetchrow_hashref() ) {
1478 $orgs{ $data->{'borrowernumber'} } = $data;
1483 } # sub get_institutions
1485 =head2 add_member_orgs
1487 add_member_orgs($borrowernumber,$borrowernumbers);
1489 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1494 sub add_member_orgs {
1495 my ( $borrowernumber, $otherborrowers ) = @_;
1496 my $dbh = C4::Context->dbh();
1498 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1499 my $sth = $dbh->prepare($query);
1500 foreach my $otherborrowernumber (@$otherborrowers) {
1501 $sth->execute( $borrowernumber, $otherborrowernumber );
1505 } # sub add_member_orgs
1507 =head2 GetCities (OUEST-PROVENCE)
1509 ($id_cityarrayref, $city_hashref) = &GetCities();
1511 Looks up the different city and zip in the database. Returns two
1512 elements: a reference-to-array, which lists the zip city
1513 codes, and a reference-to-hash, which maps the name of the city.
1514 WHERE =>OUEST PROVENCE OR EXTERIEUR
1520 #my ($type_city) = @_;
1521 my $dbh = C4::Context->dbh;
1522 my $query = qq|SELECT cityid,city_zipcode,city_name
1524 ORDER BY city_name|;
1525 my $sth = $dbh->prepare($query);
1527 #$sth->execute($type_city);
1531 # insert empty value to create a empty choice in cgi popup
1534 while ( my $data = $sth->fetchrow_hashref ) {
1535 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1536 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1539 #test to know if the table contain some records if no the function return nothing
1543 # all we have is the one blank row
1548 return ( \@id, \%city );
1552 =head2 GetSortDetails (OUEST-PROVENCE)
1554 ($lib) = &GetSortDetails($category,$sortvalue);
1556 Returns the authorized value details
1557 C<&$lib>return value of authorized value details
1558 C<&$sortvalue>this is the value of authorized value
1559 C<&$category>this is the value of authorized value category
1563 sub GetSortDetails {
1564 my ( $category, $sortvalue ) = @_;
1565 my $dbh = C4::Context->dbh;
1566 my $query = qq|SELECT lib
1567 FROM authorised_values
1569 AND authorised_value=? |;
1570 my $sth = $dbh->prepare($query);
1571 $sth->execute( $category, $sortvalue );
1572 my $lib = $sth->fetchrow;
1573 return ($lib) if ($lib);
1574 return ($sortvalue) unless ($lib);
1577 =head2 DeleteBorrower
1579 () = &DeleteBorrower($member);
1581 delete all data fo borrowers and add record to deletedborrowers table
1582 C<&$member>this is the borrowernumber
1586 sub MoveMemberToDeleted {
1588 my $dbh = C4::Context->dbh;
1590 $query = qq|SELECT *
1592 WHERE borrowernumber=?|;
1593 my $sth = $dbh->prepare($query);
1594 $sth->execute($member);
1595 my @data = $sth->fetchrow_array;
1598 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1599 . ( "?," x ( scalar(@data) - 1 ) )
1601 $sth->execute(@data);
1607 DelMember($borrowernumber);
1609 This function remove directly a borrower whitout writing it on deleteborrower.
1610 + Deletes reserves for the borrower
1615 my $dbh = C4::Context->dbh;
1616 my $borrowernumber = shift;
1617 #warn "in delmember with $borrowernumber";
1618 return unless $borrowernumber; # borrowernumber is mandatory.
1620 my $query = qq|DELETE
1622 WHERE borrowernumber=?|;
1623 my $sth = $dbh->prepare($query);
1624 $sth->execute($borrowernumber);
1629 WHERE borrowernumber = ?
1631 $sth = $dbh->prepare($query);
1632 $sth->execute($borrowernumber);
1634 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1638 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1640 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1642 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1647 sub ExtendMemberSubscriptionTo {
1648 my ( $borrowerid,$date) = @_;
1649 my $dbh = C4::Context->dbh;
1650 my $borrower = GetMember($borrowerid,'borrowernumber');
1652 $date=POSIX::strftime("%Y-%m-%d",localtime());
1653 my $borrower = GetMember($borrowerid,'borrowernumber');
1654 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1656 my $sth = $dbh->do(<<EOF);
1658 SET dateexpiry='$date'
1659 WHERE borrowernumber='$borrowerid'
1661 # add enrolmentfee if needed
1662 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1663 $sth->execute($borrower->{'categorycode'});
1664 my ($enrolmentfee) = $sth->fetchrow;
1665 if ($enrolmentfee) {
1666 # insert fee in patron debts
1667 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1669 return $date if ($sth);
1673 =head2 GetRoadTypes (OUEST-PROVENCE)
1675 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1677 Looks up the different road type . Returns two
1678 elements: a reference-to-array, which lists the id_roadtype
1679 codes, and a reference-to-hash, which maps the road type of the road .
1684 my $dbh = C4::Context->dbh;
1686 SELECT roadtypeid,road_type
1688 ORDER BY road_type|;
1689 my $sth = $dbh->prepare($query);
1694 # insert empty value to create a empty choice in cgi popup
1696 while ( my $data = $sth->fetchrow_hashref ) {
1698 push @id, $data->{'roadtypeid'};
1699 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1702 #test to know if the table contain some records if no the function return nothing
1710 return ( \@id, \%roadtype );
1716 =head2 GetTitles (OUEST-PROVENCE)
1718 ($borrowertitle)= &GetTitles();
1720 Looks up the different title . Returns array with all borrowers title
1725 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1726 unshift( @borrowerTitle, "" );
1727 my $count=@borrowerTitle;
1732 return ( \@borrowerTitle);
1736 =head2 GetPatronImage
1738 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1740 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1744 sub GetPatronImage {
1745 my ($cardnumber) = @_;
1746 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1747 my $dbh = C4::Context->dbh;
1748 my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1749 my $sth = $dbh->prepare($query);
1750 $sth->execute($cardnumber);
1751 my $imagedata = $sth->fetchrow_hashref;
1752 my $dberror = $sth->errstr;
1753 warn "Database error!" if $sth->errstr;
1755 return $imagedata, $dberror;
1758 =head2 PutPatronImage
1760 PutPatronImage($cardnumber, $mimetype, $imgfile);
1762 Stores patron binary image data and mimetype in database.
1763 NOTE: This function is good for updating images as well as inserting new images in the database.
1767 sub PutPatronImage {
1768 my ($cardnumber, $mimetype, $imgfile) = @_;
1769 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1770 my $dbh = C4::Context->dbh;
1771 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1772 my $sth = $dbh->prepare($query);
1773 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1774 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1775 my $dberror = $sth->errstr;
1780 =head2 RmPatronImage
1782 my ($dberror) = RmPatronImage($cardnumber);
1784 Removes the image for the patron with the supplied cardnumber.
1789 my ($cardnumber) = @_;
1790 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1791 my $dbh = C4::Context->dbh;
1792 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1793 my $sth = $dbh->prepare($query);
1794 $sth->execute($cardnumber);
1795 my $dberror = $sth->errstr;
1796 warn "Database error!" if $sth->errstr;
1801 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1803 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1805 Returns the description of roadtype
1806 C<&$roadtype>return description of road type
1807 C<&$roadtypeid>this is the value of roadtype s
1811 sub GetRoadTypeDetails {
1812 my ($roadtypeid) = @_;
1813 my $dbh = C4::Context->dbh;
1817 WHERE roadtypeid=?|;
1818 my $sth = $dbh->prepare($query);
1819 $sth->execute($roadtypeid);
1820 my $roadtype = $sth->fetchrow;
1824 =head2 GetBorrowersWhoHaveNotBorrowedSince
1826 &GetBorrowersWhoHaveNotBorrowedSince($date)
1828 this function get all borrowers who haven't borrowed since the date given on input arg.
1832 sub GetBorrowersWhoHaveNotBorrowedSince {
1833 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.
1835 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1836 my $filterbranch = shift ||
1837 ((C4::Context->preference('IndependantBranches')
1838 && C4::Context->userenv
1839 && C4::Context->userenv->{flags}!=1
1840 && C4::Context->userenv->{branch})
1841 ? C4::Context->userenv->{branch}
1843 my $dbh = C4::Context->dbh;
1845 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1847 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1850 if ($filterbranch && $filterbranch ne ""){
1851 $query.=" WHERE branchcode= ?";
1852 push @query_params,$filterbranch;
1854 $query.=" GROUP BY borrowers.borrowernumber";
1856 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1857 push @query_params,$filterdate;
1859 warn $query if $debug;
1860 my $sth = $dbh->prepare($query);
1861 if (scalar(@query_params)>0){
1862 $sth->execute(@query_params);
1869 while ( my $data = $sth->fetchrow_hashref ) {
1870 push @results, $data;
1875 =head2 GetBorrowersWhoHaveNeverBorrowed
1877 $results = &GetBorrowersWhoHaveNeverBorrowed
1879 this function get all borrowers who have never borrowed.
1881 I<$result> is a ref to an array which all elements are a hasref.
1885 sub GetBorrowersWhoHaveNeverBorrowed {
1886 my $filterbranch = shift ||
1887 ((C4::Context->preference('IndependantBranches')
1888 && C4::Context->userenv
1889 && C4::Context->userenv->{flags}!=1
1890 && C4::Context->userenv->{branch})
1891 ? C4::Context->userenv->{branch}
1893 my $dbh = C4::Context->dbh;
1895 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1897 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1898 WHERE issues.borrowernumber IS NULL
1901 if ($filterbranch && $filterbranch ne ""){
1902 $query.=" AND branchcode= ?";
1903 push @query_params,$filterbranch;
1905 warn $query if $debug;
1907 my $sth = $dbh->prepare($query);
1908 if (scalar(@query_params)>0){
1909 $sth->execute(@query_params);
1916 while ( my $data = $sth->fetchrow_hashref ) {
1917 push @results, $data;
1922 =head2 GetBorrowersWithIssuesHistoryOlderThan
1924 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1926 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1928 I<$result> is a ref to an array which all elements are a hashref.
1929 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1933 sub GetBorrowersWithIssuesHistoryOlderThan {
1934 my $dbh = C4::Context->dbh;
1935 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1936 my $filterbranch = shift ||
1937 ((C4::Context->preference('IndependantBranches')
1938 && C4::Context->userenv
1939 && C4::Context->userenv->{flags}!=1
1940 && C4::Context->userenv->{branch})
1941 ? C4::Context->userenv->{branch}
1944 SELECT count(borrowernumber) as n,borrowernumber
1946 WHERE returndate < ?
1947 AND borrowernumber IS NOT NULL
1950 push @query_params, $date;
1952 $query.=" AND branchcode = ?";
1953 push @query_params, $filterbranch;
1955 $query.=" GROUP BY borrowernumber ";
1956 warn $query if $debug;
1957 my $sth = $dbh->prepare($query);
1958 $sth->execute(@query_params);
1961 while ( my $data = $sth->fetchrow_hashref ) {
1962 push @results, $data;
1967 =head2 GetBorrowersNamesAndLatestIssue
1969 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1971 this function get borrowers Names and surnames and Issue information.
1973 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1974 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1978 sub GetBorrowersNamesAndLatestIssue {
1979 my $dbh = C4::Context->dbh;
1980 my @borrowernumbers=@_;
1982 SELECT surname,lastname, phone, email,max(timestamp)
1984 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1985 GROUP BY borrowernumber
1987 my $sth = $dbh->prepare($query);
1989 my $results = $sth->fetchall_arrayref({});
1992 END { } # module clean-up code here (global destructor)