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
70 &GetBorrowercategoryList
72 &GetBorrowersWhoHaveNotBorrowedSince
73 &GetBorrowersWhoHaveNeverBorrowed
74 &GetBorrowersWithIssuesHistoryOlderThan
95 &ExtendMemberSubscriptionTo
112 C4::Members - Perl Module containing convenience functions for member handling
120 This module contains routines for adding, modifying and deleting members/patrons/borrowers
128 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
130 Looks up patrons (borrowers) by name.
132 BUGFIX 499: C<$type> is now used to determine type of search.
133 if $type is "simple", search is performed on the first letter of the
136 $category_type is used to get a specified type of user.
137 (mainly adults when creating a child.)
139 C<$searchstring> is a space-separated list of search terms. Each term
140 must match the beginning a borrower's surname, first name, or other
143 C<$filter> is assumed to be a list of elements to filter results on
145 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
147 C<&SearchMember> returns a two-element list. C<$borrowers> is a
148 reference-to-array; each element is a reference-to-hash, whose keys
149 are the fields of the C<borrowers> table in the Koha database.
150 C<$count> is the number of elements in C<$borrowers>.
155 #used by member enquiries from the intranet
156 #called by member.pl and circ/circulation.pl
158 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
159 my $dbh = C4::Context->dbh;
165 # this is used by circulation everytime a new borrowers cardnumber is scanned
166 # so we can check an exact match first, if that works return, otherwise do the rest
167 $query = "SELECT * FROM borrowers
168 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
170 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
171 $sth->execute($searchstring);
172 my $data = $sth->fetchall_arrayref({});
174 return ( scalar(@$data), $data );
178 if ( $type eq "simple" ) # simple search for one letter only
180 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
181 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
182 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
183 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
184 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
187 $query.=" ORDER BY $orderby";
188 @bind = ("$searchstring%","$searchstring");
190 else # advanced search looking in surname, firstname and othernames
192 @data = split( ' ', $searchstring );
195 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
196 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
197 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
200 $query.="((surname LIKE ? OR surname LIKE ?
201 OR firstname LIKE ? OR firstname LIKE ?
202 OR othernames LIKE ? OR othernames LIKE ?)
204 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
206 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
207 "$data[0]%", "% $data[0]%"
209 for ( my $i = 1 ; $i < $count ; $i++ ) {
210 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
211 OR firstname LIKE ? OR firstname LIKE ?
212 OR othernames LIKE ? OR othernames LIKE ?)";
214 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
215 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
219 $query = $query . ") OR cardnumber LIKE ? ";
220 push( @bind, $searchstring );
221 if (C4::Context->preference('ExtendedPatronAttributes')) {
222 $query .= "OR borrowernumber IN (
223 SELECT borrowernumber
224 FROM borrower_attributes
225 JOIN borrower_attribute_types USING (code)
226 WHERE staff_searchable = 1
229 push (@bind, $searchstring);
231 $query .= "order by $orderby";
236 $sth = $dbh->prepare($query);
238 $debug and print STDERR "Q $orderby : $query\n";
239 $sth->execute(@bind);
241 $data = $sth->fetchall_arrayref({});
244 return ( scalar(@$data), $data );
247 =head2 GetMemberDetails
249 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
251 Looks up a patron and returns information about him or her. If
252 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
253 up the borrower by number; otherwise, it looks up the borrower by card
256 C<$borrower> is a reference-to-hash whose keys are the fields of the
257 borrowers table in the Koha database. In addition,
258 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
259 about the patron. Its keys act as flags :
261 if $borrower->{flags}->{LOST} {
262 # Patron's card was reported lost
265 Each flag has a C<message> key, giving a human-readable explanation of
266 the flag. If the state of a flag means that the patron should not be
267 allowed to borrow any more books, then it will have a C<noissues> key
270 The possible flags are:
276 =item Shows the patron's credit or debt, if any.
284 =item (Gone, no address.) Set if the patron has left without giving a
293 =item Set if the patron's card has been reported as lost.
301 =item Set if the patron has been debarred.
309 =item Any additional notes about the patron.
317 =item Set if the patron has overdue items. This flag has several keys:
319 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
320 overdue items. Its elements are references-to-hash, each describing an
321 overdue item. The keys are selected fields from the issues, biblio,
322 biblioitems, and items tables of the Koha database.
324 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
325 the overdue items, one per line.
333 =item Set if any items that the patron has reserved are available.
335 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
336 available items. Each element is a reference-to-hash whose keys are
337 fields from the reserves table of the Koha database.
343 sub GetMemberDetails {
344 my ( $borrowernumber, $cardnumber ) = @_;
345 my $dbh = C4::Context->dbh;
348 if ($borrowernumber) {
349 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
350 $sth->execute($borrowernumber);
352 elsif ($cardnumber) {
353 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
354 $sth->execute($cardnumber);
359 my $borrower = $sth->fetchrow_hashref;
360 my ($amount) = GetMemberAccountRecords( $borrowernumber);
361 $borrower->{'amountoutstanding'} = $amount;
362 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
363 my $flags = patronflags( $borrower);
366 $sth = $dbh->prepare("select bit,flag from userflags");
368 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
369 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
370 $accessflagshash->{$flag} = 1;
374 $borrower->{'flags'} = $flags;
375 $borrower->{'authflags'} = $accessflagshash;
377 # find out how long the membership lasts
380 "select enrolmentperiod from categories where categorycode = ?");
381 $sth->execute( $borrower->{'categorycode'} );
382 my $enrolment = $sth->fetchrow;
383 $borrower->{'enrolmentperiod'} = $enrolment;
384 return ($borrower); #, $flags, $accessflagshash);
391 NOTE!: If you change this function, be sure to update the POD for
394 $flags = &patronflags($patron);
397 {message} Message showing patron's credit or debt
398 {noissues} Set if patron owes >$5.00
399 {GNA} Set if patron gone w/o address
400 {message} "Borrower has no valid address"
402 {LOST} Set if patron's card reported lost
403 {message} Message to this effect
405 {DBARRED} Set is patron is debarred
406 {message} Message to this effect
408 {NOTES} Set if patron has notes
409 {message} Notes about patron
410 {ODUES} Set if patron has overdue books
412 {itemlist} ref-to-array: list of overdue books
413 {itemlisttext} Text list of overdue items
414 {WAITING} Set if there are items available that the
416 {message} Message to this effect
417 {itemlist} ref-to-array: list of available items
420 # FIXME rename this function.
423 my ( $patroninformation) = @_;
424 my $dbh=C4::Context->dbh;
425 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
428 my $noissuescharge = C4::Context->preference("noissuescharge");
429 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
430 $flaginfo{'amount'} = sprintf "%.02f",$amount;
431 if ( $amount > $noissuescharge ) {
432 $flaginfo{'noissues'} = 1;
434 $flags{'CHARGES'} = \%flaginfo;
436 elsif ( $amount < 0 ) {
438 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
439 $flags{'CREDITS'} = \%flaginfo;
441 if ( $patroninformation->{'gonenoaddress'}
442 && $patroninformation->{'gonenoaddress'} == 1 )
445 $flaginfo{'message'} = 'Borrower has no valid address.';
446 $flaginfo{'noissues'} = 1;
447 $flags{'GNA'} = \%flaginfo;
449 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
451 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
452 $flaginfo{'noissues'} = 1;
453 $flags{'LOST'} = \%flaginfo;
455 if ( $patroninformation->{'debarred'}
456 && $patroninformation->{'debarred'} == 1 )
459 $flaginfo{'message'} = 'Borrower is Debarred.';
460 $flaginfo{'noissues'} = 1;
461 $flags{'DBARRED'} = \%flaginfo;
463 if ( $patroninformation->{'borrowernotes'}
464 && $patroninformation->{'borrowernotes'} )
467 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
468 $flags{'NOTES'} = \%flaginfo;
470 my ( $odues, $itemsoverdue ) =
471 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
474 $flaginfo{'message'} = "Yes";
475 $flaginfo{'itemlist'} = $itemsoverdue;
476 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
479 $flaginfo{'itemlisttext'} .=
480 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
482 $flags{'ODUES'} = \%flaginfo;
484 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
485 my $nowaiting = scalar @itemswaiting;
486 if ( $nowaiting > 0 ) {
488 $flaginfo{'message'} = "Reserved items available";
489 $flaginfo{'itemlist'} = \@itemswaiting;
490 $flags{'WAITING'} = \%flaginfo;
498 $borrower = &GetMember($information, $type);
500 Looks up information about a patron (borrower) by either card number
501 ,firstname, or borrower number, depending on $type value.
502 If C<$type> == 'cardnumber', C<&GetBorrower>
503 searches by cardnumber then by firstname if not found in cardnumber;
504 otherwise, it searches by borrowernumber.
506 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
507 the C<borrowers> table in the Koha database.
513 my ( $information, $type ) = @_;
514 my $dbh = C4::Context->dbh;
517 SELECT borrowers.*, categories.category_type, categories.description
519 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
521 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
522 $information = uc $information;
523 $sth = $dbh->prepare("$select WHERE $type=?");
525 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
527 $sth->execute($information);
528 my $data = $sth->fetchrow_hashref;
530 ($data) and return ($data);
532 if ($type eq 'cardnumber' || $type eq 'firstname') { # otherwise, try with firstname
533 $sth = $dbh->prepare("$select WHERE firstname like ?");
534 $sth->execute($information);
535 $data = $sth->fetchrow_hashref;
537 ($data) and return ($data);
542 =item GetMemberIssuesAndFines
544 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
546 Returns aggregate data about items borrowed by the patron with the
547 given borrowernumber.
549 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
550 number of overdue items the patron currently has borrowed. C<$issue_count> is the
551 number of books the patron currently has borrowed. C<$total_fines> is
552 the total fine currently due by the borrower.
557 sub GetMemberIssuesAndFines {
558 my ( $borrowernumber ) = @_;
559 my $dbh = C4::Context->dbh;
560 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
562 $debug and warn $query."\n";
563 my $sth = $dbh->prepare($query);
564 $sth->execute($borrowernumber);
565 my $issue_count = $sth->fetchrow_arrayref->[0];
568 $sth = $dbh->prepare(
569 "SELECT COUNT(*) FROM issues
570 WHERE borrowernumber = ?
571 AND date_due < now()"
573 $sth->execute($borrowernumber);
574 my $overdue_count = $sth->fetchrow_arrayref->[0];
577 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
578 $sth->execute($borrowernumber);
579 my $total_fines = $sth->fetchrow_arrayref->[0];
582 return ($overdue_count, $issue_count, $total_fines);
589 &ModMember($borrowernumber);
591 Modify borrower's data. All date fields should ALREADY be in ISO format.
598 my $dbh = C4::Context->dbh;
599 my $iso_re = C4::Dates->new()->regexp('iso');
600 foreach (qw(dateofbirth dateexpiry dateenrolled)) {
601 if (my $tempdate = $data{$_}) { # assignment, not comparison
602 ($tempdate =~ /$iso_re/) and next; # Congatulations, you sent a valid ISO date.
603 warn "ModMember given $_ not in ISO format ($tempdate)";
604 if (my $tempdate2 = format_date_in_iso($tempdate)) { # assignment, not comparison
605 $data{$_} = $tempdate2;
607 warn "ModMember cannot convert '$tempdate' (from syspref)";
611 if (!$data{'dateofbirth'}){
612 undef $data{'dateofbirth'};
614 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
616 my %hashborrowerfields;
617 while (my ($field)=$qborrower->fetchrow){
618 $hashborrowerfields{$field}=1;
620 my $query = "UPDATE borrowers SET \n";
624 # test to know if you must update or not the borrower password
625 if ( $data{'password'} eq '****' ) {
626 delete $data{'password'};
628 $data{'password'} = md5_base64( $data{'password'} ) if ($data{'password'} ne "");
629 delete $data{'password'} if ($data{password} eq "");
632 { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
633 $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
634 $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
635 $sth = $dbh->prepare($query);
636 $sth->execute($data{'borrowernumber'});
639 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
640 # so when we update information for an adult we should check for guarantees and update the relevant part
641 # of their records, ie addresses and phone numbers
642 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
643 if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
644 # is adult check guarantees;
645 UpdateGuarantees(%data);
647 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})")
648 if C4::Context->preference("BorrowersLog");
656 $borrowernumber = &AddMember(%borrower);
658 insert new borrower into table
659 Returns the borrowernumber
666 my $dbh = C4::Context->dbh;
667 $data{'userid'} = '' unless $data{'password'};
668 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
670 # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
671 # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
672 # $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
673 # $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
674 # $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
675 # This query should be rewritten to use "?" at execute.
676 if (!$data{'dateofbirth'}){
677 undef ($data{'dateofbirth'});
680 "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
681 . ",surname=" . $dbh->quote( $data{'surname'} )
682 . ",firstname=" . $dbh->quote( $data{'firstname'} )
683 . ",title=" . $dbh->quote( $data{'title'} )
684 . ",othernames=" . $dbh->quote( $data{'othernames'} )
685 . ",initials=" . $dbh->quote( $data{'initials'} )
686 . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
687 . ",streettype=" . $dbh->quote( $data{'streettype'} )
688 . ",address=" . $dbh->quote( $data{'address'} )
689 . ",address2=" . $dbh->quote( $data{'address2'} )
690 . ",zipcode=" . $dbh->quote( $data{'zipcode'} )
691 . ",city=" . $dbh->quote( $data{'city'} )
692 . ",phone=" . $dbh->quote( $data{'phone'} )
693 . ",email=" . $dbh->quote( $data{'email'} )
694 . ",mobile=" . $dbh->quote( $data{'mobile'} )
695 . ",phonepro=" . $dbh->quote( $data{'phonepro'} )
696 . ",opacnote=" . $dbh->quote( $data{'opacnote'} )
697 . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
698 . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
699 . ",branchcode=" . $dbh->quote( $data{'branchcode'} )
700 . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
701 . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
702 . ",contactname=" . $dbh->quote( $data{'contactname'} )
703 . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
704 . ",dateexpiry=" . $dbh->quote( $data{'dateexpiry'} )
705 . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
706 . ",B_address=" . $dbh->quote( $data{'B_address'} )
707 . ",B_zipcode=" . $dbh->quote( $data{'B_zipcode'} )
708 . ",B_city=" . $dbh->quote( $data{'B_city'} )
709 . ",B_phone=" . $dbh->quote( $data{'B_phone'} )
710 . ",B_email=" . $dbh->quote( $data{'B_email'} )
711 . ",password=" . $dbh->quote( $data{'password'} )
712 . ",userid=" . $dbh->quote( $data{'userid'} )
713 . ",sort1=" . $dbh->quote( $data{'sort1'} )
714 . ",sort2=" . $dbh->quote( $data{'sort2'} )
715 . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
716 . ",emailpro=" . $dbh->quote( $data{'emailpro'} )
717 . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
718 . ",sex=" . $dbh->quote( $data{'sex'} )
719 . ",fax=" . $dbh->quote( $data{'fax'} )
720 . ",relationship=" . $dbh->quote( $data{'relationship'} )
721 . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
722 . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
723 . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
724 . ",lost=" . $dbh->quote( $data{'lost'} )
725 . ",debarred=" . $dbh->quote( $data{'debarred'} )
726 . ",ethnicity=" . $dbh->quote( $data{'ethnicity'} )
727 . ",ethnotes=" . $dbh->quote( $data{'ethnotes'} )
728 . ",altcontactsurname=" . $dbh->quote( $data{'altcontactsurname'} )
729 . ",altcontactfirstname=" . $dbh->quote( $data{'altcontactfirstname'} )
730 . ",altcontactaddress1=" . $dbh->quote( $data{'altcontactaddress1'} )
731 . ",altcontactaddress2=" . $dbh->quote( $data{'altcontactaddress2'} )
732 . ",altcontactaddress3=" . $dbh->quote( $data{'altcontactaddress3'} )
733 . ",altcontactzipcode=" . $dbh->quote( $data{'altcontactzipcode'} )
734 . ",altcontactphone=" . $dbh->quote( $data{'altcontactphone'} ) ;
735 $debug and print STDERR "AddMember SQL: ($query)\n";
736 my $sth = $dbh->prepare($query);
737 # print "Executing SQL: $query\n";
740 $data{'borrowernumber'} = $dbh->{'mysql_insertid'}; # unneeded w/ autoincrement ?
741 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
743 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
745 # check for enrollment fee & add it if needed
746 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
747 $sth->execute($data{'categorycode'});
748 my ($enrolmentfee) = $sth->fetchrow;
750 # insert fee in patron debts
751 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
753 return $data{'borrowernumber'};
757 my ($uid,$member) = @_;
758 my $dbh = C4::Context->dbh;
759 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
760 # Then we need to tell the user and have them create a new one.
763 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
764 $sth->execute( $uid, $member );
765 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
775 my ( $uid, $member, $digest ) = @_;
776 my $dbh = C4::Context->dbh;
778 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
779 #Then we need to tell the user and have them create a new one.
783 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
784 $sth->execute( $uid, $member );
785 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
789 #Everything is good so we can update the information.
792 "update borrowers set userid=?, password=? where borrowernumber=?");
793 $sth->execute( $uid, $digest, $member );
797 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
803 =item fixup_cardnumber
805 Warning: The caller is responsible for locking the members table in write
806 mode, to avoid database corruption.
810 use vars qw( @weightings );
811 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
813 sub fixup_cardnumber ($) {
814 my ($cardnumber) = @_;
815 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
816 $autonumber_members = 0 unless defined $autonumber_members;
818 # Find out whether member numbers should be generated
819 # automatically. Should be either "1" or something else.
820 # Defaults to "0", which is interpreted as "no".
822 # if ($cardnumber !~ /\S/ && $autonumber_members) {
823 if ($autonumber_members) {
824 my $dbh = C4::Context->dbh;
825 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
827 # if checkdigit is selected, calculate katipo-style cardnumber.
828 # otherwise, just use the max()
829 # purpose: generate checksum'd member numbers.
830 # We'll assume we just got the max value of digits 2-8 of member #'s
831 # from the database and our job is to increment that by one,
832 # determine the 1st and 9th digits and return the full string.
835 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
839 my $data = $sth->fetchrow_hashref;
840 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
842 if ( !$cardnumber ) { # If DB has no values,
843 $cardnumber = 1000000; # start at 1000000
850 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
852 # read weightings, left to right, 1 char at a time
853 my $temp1 = $weightings[$i];
855 # sequence left to right, 1 char at a time
856 my $temp2 = substr( $cardnumber, $i, 1 );
858 # mult each char 1-7 by its corresponding weighting
859 $sum += $temp1 * $temp2;
862 my $rem = ( $sum % 11 );
863 $rem = 'X' if $rem == 10;
865 $cardnumber = "V$cardnumber$rem";
869 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
870 # better. I'll leave the original in in case it needs to be changed for you
873 "select max(cast(cardnumber as signed)) from borrowers");
875 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
879 my ($result) = $sth->fetchrow;
881 $cardnumber = $result + 1;
889 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
890 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
891 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
893 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
894 with children) and looks up the borrowers who are guaranteed by that
895 borrower (i.e., the patron's children).
897 C<&GetGuarantees> returns two values: an integer giving the number of
898 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
899 of references to hash, which gives the actual results.
905 my ($borrowernumber) = @_;
906 my $dbh = C4::Context->dbh;
909 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
911 $sth->execute($borrowernumber);
914 my $data = $sth->fetchall_arrayref({});
916 return ( scalar(@$data), $data );
919 =head2 UpdateGuarantees
921 &UpdateGuarantees($parent_borrno);
924 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
925 with the modified information
930 sub UpdateGuarantees {
932 my $dbh = C4::Context->dbh;
933 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
934 for ( my $i = 0 ; $i < $count ; $i++ ) {
937 # It looks like the $i is only being returned to handle walking through
938 # the array, which is probably better done as a foreach loop.
940 my $guaquery = qq|UPDATE borrowers
941 SET address='$data{'address'}',fax='$data{'fax'}',
942 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
943 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
945 my $sth3 = $dbh->prepare($guaquery);
950 =head2 GetPendingIssues
952 ($count, $issues) = &GetPendingIssues($borrowernumber);
954 Looks up what the patron with the given borrowernumber has borrowed.
956 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
957 reference-to-array, where each element is a reference-to-hash; the
958 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
959 in the Koha database. C<$count> is the number of elements in
965 sub GetPendingIssues {
966 my ($borrowernumber) = @_;
967 my $dbh = C4::Context->dbh;
969 my $sth = $dbh->prepare(
970 "SELECT * FROM issues
971 LEFT JOIN items ON issues.itemnumber=items.itemnumber
972 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
973 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
976 ORDER BY issues.issuedate"
978 $sth->execute($borrowernumber);
979 my $data = $sth->fetchall_arrayref({});
980 my $today = POSIX::strftime("%Y%m%d", localtime);
982 my $datedue = $_->{'date_due'};
984 if ( $datedue < $today ) {
989 return ( scalar(@$data), $data );
994 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
996 Looks up what the patron with the given borrowernumber has borrowed,
997 and sorts the results.
999 C<$sortkey> is the name of a field on which to sort the results. This
1000 should be the name of a field in the C<issues>, C<biblio>,
1001 C<biblioitems>, or C<items> table in the Koha database.
1003 C<$limit> is the maximum number of results to return.
1005 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1006 reference-to-array, where each element is a reference-to-hash; the
1007 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1008 C<items> tables of the Koha database. C<$count> is the number of
1009 elements in C<$issues>
1015 my ( $borrowernumber, $order, $limit ) = @_;
1017 #FIXME: sanity-check order and limit
1018 my $dbh = C4::Context->dbh;
1021 "SELECT *,items.timestamp AS itemstimestamp
1023 LEFT JOIN items on items.itemnumber=issues.itemnumber
1024 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1025 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1026 WHERE borrowernumber=?
1028 SELECT *,items.timestamp AS itemstimestamp
1030 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1031 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1032 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1033 WHERE borrowernumber=?
1035 if ( $limit != 0 ) {
1036 $query .= " limit $limit";
1040 my $sth = $dbh->prepare($query);
1041 $sth->execute($borrowernumber, $borrowernumber);
1044 while ( my $data = $sth->fetchrow_hashref ) {
1045 $result[$i] = $data;
1050 # get all issued items for borrowernumber from oldissues table
1051 # large chunk of older issues data put into table oldissues
1052 # to speed up db calls for issuing items
1053 if ( C4::Context->preference("ReadingHistory") ) {
1054 # FIXME oldissues (not to be confused with old_issues) is
1055 # apparently specific to HLT. Not sure if the ReadingHistory
1056 # syspref is still required, as old_issues by design
1057 # is no longer checked with each loan.
1058 my $query2 = "SELECT * FROM oldissues
1059 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1060 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1061 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1062 WHERE borrowernumber=?
1064 if ( $limit != 0 ) {
1065 $limit = $limit - $count;
1066 $query2 .= " limit $limit";
1069 my $sth2 = $dbh->prepare($query2);
1070 $sth2->execute($borrowernumber);
1072 while ( my $data2 = $sth2->fetchrow_hashref ) {
1073 $result[$i] = $data2;
1080 return ( $i, \@result );
1084 =head2 GetMemberAccountRecords
1086 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1088 Looks up accounting data for the patron with the given borrowernumber.
1090 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1091 reference-to-array, where each element is a reference-to-hash; the
1092 keys are the fields of the C<accountlines> table in the Koha database.
1093 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1094 total amount outstanding for all of the account lines.
1099 sub GetMemberAccountRecords {
1100 my ($borrowernumber,$date) = @_;
1101 my $dbh = C4::Context->dbh;
1107 WHERE borrowernumber=?);
1108 my @bind = ($borrowernumber);
1109 if ($date && $date ne ''){
1110 $strsth.=" AND date < ? ";
1113 $strsth.=" ORDER BY date desc,timestamp DESC";
1114 my $sth= $dbh->prepare( $strsth );
1115 $sth->execute( @bind );
1117 while ( my $data = $sth->fetchrow_hashref ) {
1118 $acctlines[$numlines] = $data;
1120 $total += $data->{'amountoutstanding'};
1123 return ( $total, \@acctlines,$numlines);
1126 =head2 GetBorNotifyAcctRecord
1128 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1130 Looks up accounting data for the patron with the given borrowernumber per file number.
1132 (FIXME - I'm not at all sure what this is about.)
1134 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1135 reference-to-array, where each element is a reference-to-hash; the
1136 keys are the fields of the C<accountlines> table in the Koha database.
1137 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1138 total amount outstanding for all of the account lines.
1142 sub GetBorNotifyAcctRecord {
1143 my ( $borrowernumber, $notifyid ) = @_;
1144 my $dbh = C4::Context->dbh;
1147 my $sth = $dbh->prepare(
1150 WHERE borrowernumber=?
1152 AND amountoutstanding != '0'
1153 ORDER BY notify_id,accounttype
1155 # 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')
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,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1172 Checks that a member exists or not in the database.
1174 C<&result> is nonzero (=exist) or 0 (=does not exist)
1175 C<&categorycode> is from categorycode table
1176 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1177 C<&surname> is the surname
1178 C<&firstname> is the firstname (only if collectivity=0)
1179 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1183 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1184 # This is especially true since first name is not even a required field.
1186 sub checkuniquemember {
1187 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1188 my $dbh = C4::Context->dbh;
1189 my $request = ($collectivity) ?
1190 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1191 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1192 my $sth = $dbh->prepare($request);
1193 if ($collectivity) {
1194 $sth->execute( uc($surname) );
1196 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1198 my @data = $sth->fetchrow;
1200 ( $data[0] ) and return $data[0], $data[1];
1204 sub checkcardnumber {
1205 my ($cardnumber,$borrowernumber) = @_;
1206 my $dbh = C4::Context->dbh;
1207 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1208 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1209 my $sth = $dbh->prepare($query);
1210 if ($borrowernumber) {
1211 $sth->execute($cardnumber,$borrowernumber);
1213 $sth->execute($cardnumber);
1215 if (my $data= $sth->fetchrow_hashref()){
1225 =head2 getzipnamecity (OUEST-PROVENCE)
1227 take all info from table city for the fields city and zip
1228 check for the name and the zip code of the city selected
1232 sub getzipnamecity {
1234 my $dbh = C4::Context->dbh;
1237 "select city_name,city_zipcode from cities where cityid=? ");
1238 $sth->execute($cityid);
1239 my @data = $sth->fetchrow;
1240 return $data[0], $data[1];
1244 =head2 getdcity (OUEST-PROVENCE)
1246 recover cityid with city_name condition
1251 my ($city_name) = @_;
1252 my $dbh = C4::Context->dbh;
1253 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1254 $sth->execute($city_name);
1255 my $data = $sth->fetchrow;
1260 =head2 GetExpiryDate
1262 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1264 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1265 Return date is also in ISO format.
1270 my ( $categorycode, $dateenrolled ) = @_;
1271 my $enrolmentperiod = 12; # reasonable default
1272 if ($categorycode) {
1273 my $dbh = C4::Context->dbh;
1274 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1275 $sth->execute($categorycode);
1276 $enrolmentperiod = $sth->fetchrow;
1278 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1279 my @date = split /-/,$dateenrolled;
1280 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1283 =head2 checkuserpassword (OUEST-PROVENCE)
1285 check for the password and login are not used
1286 return the number of record
1287 0=> NOT USED 1=> USED
1291 sub checkuserpassword {
1292 my ( $borrowernumber, $userid, $password ) = @_;
1293 $password = md5_base64($password);
1294 my $dbh = C4::Context->dbh;
1297 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1299 $sth->execute( $borrowernumber, $userid, $password );
1300 my $number_rows = $sth->fetchrow;
1301 return $number_rows;
1305 =head2 GetborCatFromCatType
1307 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1309 Looks up the different types of borrowers in the database. Returns two
1310 elements: a reference-to-array, which lists the borrower category
1311 codes, and a reference-to-hash, which maps the borrower category codes
1312 to category descriptions.
1317 sub GetborCatFromCatType {
1318 my ( $category_type, $action ) = @_;
1319 my $dbh = C4::Context->dbh;
1320 my $request = qq| SELECT categorycode,description
1323 ORDER BY categorycode|;
1324 my $sth = $dbh->prepare($request);
1326 $sth->execute($category_type);
1335 while ( my $data = $sth->fetchrow_hashref ) {
1336 push @codes, $data->{'categorycode'};
1337 $labels{ $data->{'categorycode'} } = $data->{'description'};
1340 return ( \@codes, \%labels );
1343 =head2 GetBorrowercategory
1345 $hashref = &GetBorrowercategory($categorycode);
1347 Given the borrower's category code, the function returns the corresponding
1348 data hashref for a comprehensive information display.
1350 $arrayref_hashref = &GetBorrowercategory;
1351 If no category code provided, the function returns all the categories.
1355 sub GetBorrowercategory {
1357 my $dbh = C4::Context->dbh;
1361 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1363 WHERE categorycode = ?"
1365 $sth->execute($catcode);
1367 $sth->fetchrow_hashref;
1372 } # sub getborrowercategory
1374 =head2 GetBorrowercategoryList
1376 $arrayref_hashref = &GetBorrowercategoryList;
1377 If no category code provided, the function returns all the categories.
1381 sub GetBorrowercategoryList {
1382 my $dbh = C4::Context->dbh;
1387 ORDER BY description"
1391 $sth->fetchall_arrayref({});
1394 } # sub getborrowercategory
1396 =head2 ethnicitycategories
1398 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1400 Looks up the different ethnic types in the database. Returns two
1401 elements: a reference-to-array, which lists the ethnicity codes, and a
1402 reference-to-hash, which maps the ethnicity codes to ethnicity
1409 sub ethnicitycategories {
1410 my $dbh = C4::Context->dbh;
1411 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1415 while ( my $data = $sth->fetchrow_hashref ) {
1416 push @codes, $data->{'code'};
1417 $labels{ $data->{'code'} } = $data->{'name'};
1420 return ( \@codes, \%labels );
1425 $ethn_name = &fixEthnicity($ethn_code);
1427 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1428 corresponding descriptive name from the C<ethnicity> table in the
1429 Koha database ("European" or "Pacific Islander").
1436 my $ethnicity = shift;
1437 return unless $ethnicity;
1438 my $dbh = C4::Context->dbh;
1439 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1440 $sth->execute($ethnicity);
1441 my $data = $sth->fetchrow_hashref;
1443 return $data->{'name'};
1444 } # sub fixEthnicity
1448 $dateofbirth,$date = &GetAge($date);
1450 this function return the borrowers age with the value of dateofbirth
1456 my ( $date, $date_ref ) = @_;
1458 if ( not defined $date_ref ) {
1459 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1462 my ( $year1, $month1, $day1 ) = split /-/, $date;
1463 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1465 my $age = $year2 - $year1;
1466 if ( $month1 . $day1 > $month2 . $day2 ) {
1473 =head2 get_institutions
1474 $insitutions = get_institutions();
1476 Just returns a list of all the borrowers of type I, borrownumber and name
1481 sub get_institutions {
1482 my $dbh = C4::Context->dbh();
1485 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1489 while ( my $data = $sth->fetchrow_hashref() ) {
1490 $orgs{ $data->{'borrowernumber'} } = $data;
1495 } # sub get_institutions
1497 =head2 add_member_orgs
1499 add_member_orgs($borrowernumber,$borrowernumbers);
1501 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1506 sub add_member_orgs {
1507 my ( $borrowernumber, $otherborrowers ) = @_;
1508 my $dbh = C4::Context->dbh();
1510 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1511 my $sth = $dbh->prepare($query);
1512 foreach my $otherborrowernumber (@$otherborrowers) {
1513 $sth->execute( $borrowernumber, $otherborrowernumber );
1517 } # sub add_member_orgs
1519 =head2 GetCities (OUEST-PROVENCE)
1521 ($id_cityarrayref, $city_hashref) = &GetCities();
1523 Looks up the different city and zip in the database. Returns two
1524 elements: a reference-to-array, which lists the zip city
1525 codes, and a reference-to-hash, which maps the name of the city.
1526 WHERE =>OUEST PROVENCE OR EXTERIEUR
1532 #my ($type_city) = @_;
1533 my $dbh = C4::Context->dbh;
1534 my $query = qq|SELECT cityid,city_zipcode,city_name
1536 ORDER BY city_name|;
1537 my $sth = $dbh->prepare($query);
1539 #$sth->execute($type_city);
1543 # insert empty value to create a empty choice in cgi popup
1546 while ( my $data = $sth->fetchrow_hashref ) {
1547 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1548 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1551 #test to know if the table contain some records if no the function return nothing
1555 # all we have is the one blank row
1560 return ( \@id, \%city );
1564 =head2 GetSortDetails (OUEST-PROVENCE)
1566 ($lib) = &GetSortDetails($category,$sortvalue);
1568 Returns the authorized value details
1569 C<&$lib>return value of authorized value details
1570 C<&$sortvalue>this is the value of authorized value
1571 C<&$category>this is the value of authorized value category
1575 sub GetSortDetails {
1576 my ( $category, $sortvalue ) = @_;
1577 my $dbh = C4::Context->dbh;
1578 my $query = qq|SELECT lib
1579 FROM authorised_values
1581 AND authorised_value=? |;
1582 my $sth = $dbh->prepare($query);
1583 $sth->execute( $category, $sortvalue );
1584 my $lib = $sth->fetchrow;
1585 return ($lib) if ($lib);
1586 return ($sortvalue) unless ($lib);
1589 =head2 DeleteBorrower
1591 () = &DeleteBorrower($member);
1593 delete all data fo borrowers and add record to deletedborrowers table
1594 C<&$member>this is the borrowernumber
1598 sub MoveMemberToDeleted {
1600 my $dbh = C4::Context->dbh;
1602 $query = qq|SELECT *
1604 WHERE borrowernumber=?|;
1605 my $sth = $dbh->prepare($query);
1606 $sth->execute($member);
1607 my @data = $sth->fetchrow_array;
1610 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1611 . ( "?," x ( scalar(@data) - 1 ) )
1613 $sth->execute(@data);
1619 DelMember($borrowernumber);
1621 This function remove directly a borrower whitout writing it on deleteborrower.
1622 + Deletes reserves for the borrower
1627 my $dbh = C4::Context->dbh;
1628 my $borrowernumber = shift;
1629 #warn "in delmember with $borrowernumber";
1630 return unless $borrowernumber; # borrowernumber is mandatory.
1632 my $query = qq|DELETE
1634 WHERE borrowernumber=?|;
1635 my $sth = $dbh->prepare($query);
1636 $sth->execute($borrowernumber);
1641 WHERE borrowernumber = ?
1643 $sth = $dbh->prepare($query);
1644 $sth->execute($borrowernumber);
1646 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1650 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1652 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1654 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1659 sub ExtendMemberSubscriptionTo {
1660 my ( $borrowerid,$date) = @_;
1661 my $dbh = C4::Context->dbh;
1662 my $borrower = GetMember($borrowerid,'borrowernumber');
1664 $date=POSIX::strftime("%Y-%m-%d",localtime());
1665 my $borrower = GetMember($borrowerid,'borrowernumber');
1666 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1668 my $sth = $dbh->do(<<EOF);
1670 SET dateexpiry='$date'
1671 WHERE borrowernumber='$borrowerid'
1673 # add enrolmentfee if needed
1674 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1675 $sth->execute($borrower->{'categorycode'});
1676 my ($enrolmentfee) = $sth->fetchrow;
1677 if ($enrolmentfee) {
1678 # insert fee in patron debts
1679 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1681 return $date if ($sth);
1685 =head2 GetRoadTypes (OUEST-PROVENCE)
1687 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1689 Looks up the different road type . Returns two
1690 elements: a reference-to-array, which lists the id_roadtype
1691 codes, and a reference-to-hash, which maps the road type of the road .
1696 my $dbh = C4::Context->dbh;
1698 SELECT roadtypeid,road_type
1700 ORDER BY road_type|;
1701 my $sth = $dbh->prepare($query);
1706 # insert empty value to create a empty choice in cgi popup
1708 while ( my $data = $sth->fetchrow_hashref ) {
1710 push @id, $data->{'roadtypeid'};
1711 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1714 #test to know if the table contain some records if no the function return nothing
1722 return ( \@id, \%roadtype );
1728 =head2 GetTitles (OUEST-PROVENCE)
1730 ($borrowertitle)= &GetTitles();
1732 Looks up the different title . Returns array with all borrowers title
1737 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1738 unshift( @borrowerTitle, "" );
1739 my $count=@borrowerTitle;
1744 return ( \@borrowerTitle);
1748 =head2 GetPatronImage
1750 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1752 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1756 sub GetPatronImage {
1757 my ($cardnumber) = @_;
1758 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1759 my $dbh = C4::Context->dbh;
1760 my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1761 my $sth = $dbh->prepare($query);
1762 $sth->execute($cardnumber);
1763 my $imagedata = $sth->fetchrow_hashref;
1764 my $dberror = $sth->errstr;
1765 warn "Database error!" if $sth->errstr;
1767 return $imagedata, $dberror;
1770 =head2 PutPatronImage
1772 PutPatronImage($cardnumber, $mimetype, $imgfile);
1774 Stores patron binary image data and mimetype in database.
1775 NOTE: This function is good for updating images as well as inserting new images in the database.
1779 sub PutPatronImage {
1780 my ($cardnumber, $mimetype, $imgfile) = @_;
1781 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1782 my $dbh = C4::Context->dbh;
1783 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1784 my $sth = $dbh->prepare($query);
1785 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1786 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1787 my $dberror = $sth->errstr;
1792 =head2 RmPatronImage
1794 my ($dberror) = RmPatronImage($cardnumber);
1796 Removes the image for the patron with the supplied cardnumber.
1801 my ($cardnumber) = @_;
1802 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1803 my $dbh = C4::Context->dbh;
1804 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1805 my $sth = $dbh->prepare($query);
1806 $sth->execute($cardnumber);
1807 my $dberror = $sth->errstr;
1808 warn "Database error!" if $sth->errstr;
1813 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1815 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1817 Returns the description of roadtype
1818 C<&$roadtype>return description of road type
1819 C<&$roadtypeid>this is the value of roadtype s
1823 sub GetRoadTypeDetails {
1824 my ($roadtypeid) = @_;
1825 my $dbh = C4::Context->dbh;
1829 WHERE roadtypeid=?|;
1830 my $sth = $dbh->prepare($query);
1831 $sth->execute($roadtypeid);
1832 my $roadtype = $sth->fetchrow;
1836 =head2 GetBorrowersWhoHaveNotBorrowedSince
1838 &GetBorrowersWhoHaveNotBorrowedSince($date)
1840 this function get all borrowers who haven't borrowed since the date given on input arg.
1844 sub GetBorrowersWhoHaveNotBorrowedSince {
1845 ### 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.
1847 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1848 my $filterbranch = shift ||
1849 ((C4::Context->preference('IndependantBranches')
1850 && C4::Context->userenv
1851 && C4::Context->userenv->{flags}!=1
1852 && C4::Context->userenv->{branch})
1853 ? C4::Context->userenv->{branch}
1855 my $dbh = C4::Context->dbh;
1857 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1859 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1862 if ($filterbranch && $filterbranch ne ""){
1863 $query.=" WHERE branchcode= ?";
1864 push @query_params,$filterbranch;
1866 $query.=" GROUP BY borrowers.borrowernumber";
1868 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1869 push @query_params,$filterdate;
1871 warn $query if $debug;
1872 my $sth = $dbh->prepare($query);
1873 if (scalar(@query_params)>0){
1874 $sth->execute(@query_params);
1881 while ( my $data = $sth->fetchrow_hashref ) {
1882 push @results, $data;
1887 =head2 GetBorrowersWhoHaveNeverBorrowed
1889 $results = &GetBorrowersWhoHaveNeverBorrowed
1891 this function get all borrowers who have never borrowed.
1893 I<$result> is a ref to an array which all elements are a hasref.
1897 sub GetBorrowersWhoHaveNeverBorrowed {
1898 my $filterbranch = shift ||
1899 ((C4::Context->preference('IndependantBranches')
1900 && C4::Context->userenv
1901 && C4::Context->userenv->{flags}!=1
1902 && C4::Context->userenv->{branch})
1903 ? C4::Context->userenv->{branch}
1905 my $dbh = C4::Context->dbh;
1907 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1909 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1910 WHERE issues.borrowernumber IS NULL
1913 if ($filterbranch && $filterbranch ne ""){
1914 $query.=" AND branchcode= ?";
1915 push @query_params,$filterbranch;
1917 warn $query if $debug;
1919 my $sth = $dbh->prepare($query);
1920 if (scalar(@query_params)>0){
1921 $sth->execute(@query_params);
1928 while ( my $data = $sth->fetchrow_hashref ) {
1929 push @results, $data;
1934 =head2 GetBorrowersWithIssuesHistoryOlderThan
1936 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1938 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1940 I<$result> is a ref to an array which all elements are a hashref.
1941 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1945 sub GetBorrowersWithIssuesHistoryOlderThan {
1946 my $dbh = C4::Context->dbh;
1947 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1948 my $filterbranch = shift ||
1949 ((C4::Context->preference('IndependantBranches')
1950 && C4::Context->userenv
1951 && C4::Context->userenv->{flags}!=1
1952 && C4::Context->userenv->{branch})
1953 ? C4::Context->userenv->{branch}
1956 SELECT count(borrowernumber) as n,borrowernumber
1958 WHERE returndate < ?
1959 AND borrowernumber IS NOT NULL
1962 push @query_params, $date;
1964 $query.=" AND branchcode = ?";
1965 push @query_params, $filterbranch;
1967 $query.=" GROUP BY borrowernumber ";
1968 warn $query if $debug;
1969 my $sth = $dbh->prepare($query);
1970 $sth->execute(@query_params);
1973 while ( my $data = $sth->fetchrow_hashref ) {
1974 push @results, $data;
1979 =head2 GetBorrowersNamesAndLatestIssue
1981 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1983 this function get borrowers Names and surnames and Issue information.
1985 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1986 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1990 sub GetBorrowersNamesAndLatestIssue {
1991 my $dbh = C4::Context->dbh;
1992 my @borrowernumbers=@_;
1994 SELECT surname,lastname, phone, email,max(timestamp)
1996 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1997 GROUP BY borrowernumber
1999 my $sth = $dbh->prepare($query);
2001 my $results = $sth->fetchall_arrayref({});
2004 END { } # module clean-up code here (global destructor)