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 ?
220 push( @bind, $searchstring );
225 $sth = $dbh->prepare($query);
227 $debug and print STDERR "Q $orderby : $query\n";
228 $sth->execute(@bind);
230 $data = $sth->fetchall_arrayref({});
233 return ( scalar(@$data), $data );
236 =head2 GetMemberDetails
238 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
240 Looks up a patron and returns information about him or her. If
241 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
242 up the borrower by number; otherwise, it looks up the borrower by card
245 C<$borrower> is a reference-to-hash whose keys are the fields of the
246 borrowers table in the Koha database. In addition,
247 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
248 about the patron. Its keys act as flags :
250 if $borrower->{flags}->{LOST} {
251 # Patron's card was reported lost
254 Each flag has a C<message> key, giving a human-readable explanation of
255 the flag. If the state of a flag means that the patron should not be
256 allowed to borrow any more books, then it will have a C<noissues> key
259 The possible flags are:
265 =item Shows the patron's credit or debt, if any.
273 =item (Gone, no address.) Set if the patron has left without giving a
282 =item Set if the patron's card has been reported as lost.
290 =item Set if the patron has been debarred.
298 =item Any additional notes about the patron.
306 =item Set if the patron has overdue items. This flag has several keys:
308 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
309 overdue items. Its elements are references-to-hash, each describing an
310 overdue item. The keys are selected fields from the issues, biblio,
311 biblioitems, and items tables of the Koha database.
313 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
314 the overdue items, one per line.
322 =item Set if any items that the patron has reserved are available.
324 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
325 available items. Each element is a reference-to-hash whose keys are
326 fields from the reserves table of the Koha database.
332 sub GetMemberDetails {
333 my ( $borrowernumber, $cardnumber ) = @_;
334 my $dbh = C4::Context->dbh;
337 if ($borrowernumber) {
338 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
339 $sth->execute($borrowernumber);
341 elsif ($cardnumber) {
342 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
343 $sth->execute($cardnumber);
348 my $borrower = $sth->fetchrow_hashref;
349 my ($amount) = GetMemberAccountRecords( $borrowernumber);
350 $borrower->{'amountoutstanding'} = $amount;
351 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
352 my $flags = patronflags( $borrower);
355 $sth = $dbh->prepare("select bit,flag from userflags");
357 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
358 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
359 $accessflagshash->{$flag} = 1;
363 $borrower->{'flags'} = $flags;
364 $borrower->{'authflags'} = $accessflagshash;
366 # find out how long the membership lasts
369 "select enrolmentperiod from categories where categorycode = ?");
370 $sth->execute( $borrower->{'categorycode'} );
371 my $enrolment = $sth->fetchrow;
372 $borrower->{'enrolmentperiod'} = $enrolment;
373 return ($borrower); #, $flags, $accessflagshash);
380 NOTE!: If you change this function, be sure to update the POD for
383 $flags = &patronflags($patron);
386 {message} Message showing patron's credit or debt
387 {noissues} Set if patron owes >$5.00
388 {GNA} Set if patron gone w/o address
389 {message} "Borrower has no valid address"
391 {LOST} Set if patron's card reported lost
392 {message} Message to this effect
394 {DBARRED} Set is patron is debarred
395 {message} Message to this effect
397 {NOTES} Set if patron has notes
398 {message} Notes about patron
399 {ODUES} Set if patron has overdue books
401 {itemlist} ref-to-array: list of overdue books
402 {itemlisttext} Text list of overdue items
403 {WAITING} Set if there are items available that the
405 {message} Message to this effect
406 {itemlist} ref-to-array: list of available items
409 # FIXME rename this function.
412 my ( $patroninformation) = @_;
413 my $dbh=C4::Context->dbh;
414 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
417 my $noissuescharge = C4::Context->preference("noissuescharge");
418 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
419 $flaginfo{'amount'} = sprintf "%.02f",$amount;
420 if ( $amount > $noissuescharge ) {
421 $flaginfo{'noissues'} = 1;
423 $flags{'CHARGES'} = \%flaginfo;
425 elsif ( $amount < 0 ) {
427 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
428 $flags{'CREDITS'} = \%flaginfo;
430 if ( $patroninformation->{'gonenoaddress'}
431 && $patroninformation->{'gonenoaddress'} == 1 )
434 $flaginfo{'message'} = 'Borrower has no valid address.';
435 $flaginfo{'noissues'} = 1;
436 $flags{'GNA'} = \%flaginfo;
438 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
440 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
441 $flaginfo{'noissues'} = 1;
442 $flags{'LOST'} = \%flaginfo;
444 if ( $patroninformation->{'debarred'}
445 && $patroninformation->{'debarred'} == 1 )
448 $flaginfo{'message'} = 'Borrower is Debarred.';
449 $flaginfo{'noissues'} = 1;
450 $flags{'DBARRED'} = \%flaginfo;
452 if ( $patroninformation->{'borrowernotes'}
453 && $patroninformation->{'borrowernotes'} )
456 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
457 $flags{'NOTES'} = \%flaginfo;
459 my ( $odues, $itemsoverdue ) =
460 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
463 $flaginfo{'message'} = "Yes";
464 $flaginfo{'itemlist'} = $itemsoverdue;
465 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
468 $flaginfo{'itemlisttext'} .=
469 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
471 $flags{'ODUES'} = \%flaginfo;
473 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
474 my $nowaiting = scalar @itemswaiting;
475 if ( $nowaiting > 0 ) {
477 $flaginfo{'message'} = "Reserved items available";
478 $flaginfo{'itemlist'} = \@itemswaiting;
479 $flags{'WAITING'} = \%flaginfo;
487 $borrower = &GetMember($information, $type);
489 Looks up information about a patron (borrower) by either card number
490 ,firstname, or borrower number, depending on $type value.
491 If C<$type> == 'cardnumber', C<&GetBorrower>
492 searches by cardnumber then by firstname if not found in cardnumber;
493 otherwise, it searches by borrowernumber.
495 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
496 the C<borrowers> table in the Koha database.
502 my ( $information, $type ) = @_;
503 my $dbh = C4::Context->dbh;
506 SELECT borrowers.*, categories.category_type, categories.description
508 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
510 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
511 $information = uc $information;
512 $sth = $dbh->prepare("$select WHERE $type=?");
514 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
516 $sth->execute($information);
517 my $data = $sth->fetchrow_hashref;
519 ($data) and return ($data);
521 if ($type eq 'cardnumber' || $type eq 'firstname') { # otherwise, try with firstname
522 $sth = $dbh->prepare("$select WHERE firstname like ?");
523 $sth->execute($information);
524 $data = $sth->fetchrow_hashref;
526 ($data) and return ($data);
531 =item GetMemberIssuesAndFines
533 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
535 Returns aggregate data about items borrowed by the patron with the
536 given borrowernumber.
538 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
539 number of overdue items the patron currently has borrowed. C<$issue_count> is the
540 number of books the patron currently has borrowed. C<$total_fines> is
541 the total fine currently due by the borrower.
546 sub GetMemberIssuesAndFines {
547 my ( $borrowernumber ) = @_;
548 my $dbh = C4::Context->dbh;
549 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
551 $debug and warn $query."\n";
552 my $sth = $dbh->prepare($query);
553 $sth->execute($borrowernumber);
554 my $issue_count = $sth->fetchrow_arrayref->[0];
557 $sth = $dbh->prepare(
558 "SELECT COUNT(*) FROM issues
559 WHERE borrowernumber = ?
560 AND date_due < now()"
562 $sth->execute($borrowernumber);
563 my $overdue_count = $sth->fetchrow_arrayref->[0];
566 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
567 $sth->execute($borrowernumber);
568 my $total_fines = $sth->fetchrow_arrayref->[0];
571 return ($overdue_count, $issue_count, $total_fines);
578 &ModMember($borrowernumber);
580 Modify borrower's data. All date fields should ALREADY be in ISO format.
587 my $dbh = C4::Context->dbh;
588 my $iso_re = C4::Dates->new()->regexp('iso');
589 foreach (qw(dateofbirth dateexpiry dateenrolled)) {
590 if (my $tempdate = $data{$_}) { # assignment, not comparison
591 ($tempdate =~ /$iso_re/) and next; # Congatulations, you sent a valid ISO date.
592 warn "ModMember given $_ not in ISO format ($tempdate)";
593 if (my $tempdate2 = format_date_in_iso($tempdate)) { # assignment, not comparison
594 $data{$_} = $tempdate2;
596 warn "ModMember cannot convert '$tempdate' (from syspref)";
600 if (!$data{'dateofbirth'}){
601 undef $data{'dateofbirth'};
603 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
605 my %hashborrowerfields;
606 while (my ($field)=$qborrower->fetchrow){
607 $hashborrowerfields{$field}=1;
609 my $query = "UPDATE borrowers SET \n";
613 # test to know if you must update or not the borrower password
614 if ( $data{'password'} eq '****' ) {
615 delete $data{'password'};
617 $data{'password'} = md5_base64( $data{'password'} ) if ($data{'password'} ne "");
618 delete $data{'password'} if ($data{password} eq "");
621 { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
622 $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
623 $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
624 $sth = $dbh->prepare($query);
625 $sth->execute($data{'borrowernumber'});
628 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
629 # so when we update information for an adult we should check for guarantees and update the relevant part
630 # of their records, ie addresses and phone numbers
631 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
632 if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
633 # is adult check guarantees;
634 UpdateGuarantees(%data);
636 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})")
637 if C4::Context->preference("BorrowersLog");
645 $borrowernumber = &AddMember(%borrower);
647 insert new borrower into table
648 Returns the borrowernumber
655 my $dbh = C4::Context->dbh;
656 $data{'userid'} = '' unless $data{'password'};
657 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
659 # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
660 # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
661 # $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
662 # $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
663 # $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
664 # This query should be rewritten to use "?" at execute.
665 if (!$data{'dateofbirth'}){
666 undef ($data{'dateofbirth'});
669 "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
670 . ",surname=" . $dbh->quote( $data{'surname'} )
671 . ",firstname=" . $dbh->quote( $data{'firstname'} )
672 . ",title=" . $dbh->quote( $data{'title'} )
673 . ",othernames=" . $dbh->quote( $data{'othernames'} )
674 . ",initials=" . $dbh->quote( $data{'initials'} )
675 . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
676 . ",streettype=" . $dbh->quote( $data{'streettype'} )
677 . ",address=" . $dbh->quote( $data{'address'} )
678 . ",address2=" . $dbh->quote( $data{'address2'} )
679 . ",zipcode=" . $dbh->quote( $data{'zipcode'} )
680 . ",city=" . $dbh->quote( $data{'city'} )
681 . ",phone=" . $dbh->quote( $data{'phone'} )
682 . ",email=" . $dbh->quote( $data{'email'} )
683 . ",mobile=" . $dbh->quote( $data{'mobile'} )
684 . ",phonepro=" . $dbh->quote( $data{'phonepro'} )
685 . ",opacnote=" . $dbh->quote( $data{'opacnote'} )
686 . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
687 . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
688 . ",branchcode=" . $dbh->quote( $data{'branchcode'} )
689 . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
690 . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
691 . ",contactname=" . $dbh->quote( $data{'contactname'} )
692 . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
693 . ",dateexpiry=" . $dbh->quote( $data{'dateexpiry'} )
694 . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
695 . ",B_address=" . $dbh->quote( $data{'B_address'} )
696 . ",B_zipcode=" . $dbh->quote( $data{'B_zipcode'} )
697 . ",B_city=" . $dbh->quote( $data{'B_city'} )
698 . ",B_phone=" . $dbh->quote( $data{'B_phone'} )
699 . ",B_email=" . $dbh->quote( $data{'B_email'} )
700 . ",password=" . $dbh->quote( $data{'password'} )
701 . ",userid=" . $dbh->quote( $data{'userid'} )
702 . ",sort1=" . $dbh->quote( $data{'sort1'} )
703 . ",sort2=" . $dbh->quote( $data{'sort2'} )
704 . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
705 . ",emailpro=" . $dbh->quote( $data{'emailpro'} )
706 . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
707 . ",sex=" . $dbh->quote( $data{'sex'} )
708 . ",fax=" . $dbh->quote( $data{'fax'} )
709 . ",relationship=" . $dbh->quote( $data{'relationship'} )
710 . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
711 . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
712 . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
713 . ",lost=" . $dbh->quote( $data{'lost'} )
714 . ",debarred=" . $dbh->quote( $data{'debarred'} )
715 . ",ethnicity=" . $dbh->quote( $data{'ethnicity'} )
716 . ",ethnotes=" . $dbh->quote( $data{'ethnotes'} )
717 . ",altcontactsurname=" . $dbh->quote( $data{'altcontactsurname'} )
718 . ",altcontactfirstname=" . $dbh->quote( $data{'altcontactfirstname'} )
719 . ",altcontactaddress1=" . $dbh->quote( $data{'altcontactaddress1'} )
720 . ",altcontactaddress2=" . $dbh->quote( $data{'altcontactaddress2'} )
721 . ",altcontactaddress3=" . $dbh->quote( $data{'altcontactaddress3'} )
722 . ",altcontactzipcode=" . $dbh->quote( $data{'altcontactzipcode'} )
723 . ",altcontactphone=" . $dbh->quote( $data{'altcontactphone'} ) ;
724 $debug and print STDERR "AddMember SQL: ($query)\n";
725 my $sth = $dbh->prepare($query);
726 # print "Executing SQL: $query\n";
729 $data{'borrowernumber'} = $dbh->{'mysql_insertid'}; # unneeded w/ autoincrement ?
730 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
732 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
734 # check for enrollment fee & add it if needed
735 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
736 $sth->execute($data{'categorycode'});
737 my ($enrolmentfee) = $sth->fetchrow;
739 # insert fee in patron debts
740 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
742 return $data{'borrowernumber'};
746 my ($uid,$member) = @_;
747 my $dbh = C4::Context->dbh;
748 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
749 # Then we need to tell the user and have them create a new one.
752 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
753 $sth->execute( $uid, $member );
754 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
764 my ( $uid, $member, $digest ) = @_;
765 my $dbh = C4::Context->dbh;
767 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
768 #Then we need to tell the user and have them create a new one.
771 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
772 $sth->execute( $uid, $member );
773 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
777 #Everything is good so we can update the information.
780 "update borrowers set userid=?, password=? where borrowernumber=?");
781 $sth->execute( $uid, $digest, $member );
785 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
790 =item fixup_cardnumber
792 Warning: The caller is responsible for locking the members table in write
793 mode, to avoid database corruption.
797 use vars qw( @weightings );
798 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
800 sub fixup_cardnumber ($) {
801 my ($cardnumber) = @_;
802 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
803 $autonumber_members = 0 unless defined $autonumber_members;
805 # Find out whether member numbers should be generated
806 # automatically. Should be either "1" or something else.
807 # Defaults to "0", which is interpreted as "no".
809 # if ($cardnumber !~ /\S/ && $autonumber_members) {
810 if ($autonumber_members) {
811 my $dbh = C4::Context->dbh;
812 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
814 # if checkdigit is selected, calculate katipo-style cardnumber.
815 # otherwise, just use the max()
816 # purpose: generate checksum'd member numbers.
817 # We'll assume we just got the max value of digits 2-8 of member #'s
818 # from the database and our job is to increment that by one,
819 # determine the 1st and 9th digits and return the full string.
822 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
826 my $data = $sth->fetchrow_hashref;
827 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
829 if ( !$cardnumber ) { # If DB has no values,
830 $cardnumber = 1000000; # start at 1000000
837 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
839 # read weightings, left to right, 1 char at a time
840 my $temp1 = $weightings[$i];
842 # sequence left to right, 1 char at a time
843 my $temp2 = substr( $cardnumber, $i, 1 );
845 # mult each char 1-7 by its corresponding weighting
846 $sum += $temp1 * $temp2;
849 my $rem = ( $sum % 11 );
850 $rem = 'X' if $rem == 10;
852 $cardnumber = "V$cardnumber$rem";
856 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
857 # better. I'll leave the original in in case it needs to be changed for you
860 "select max(cast(cardnumber as signed)) from borrowers");
862 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
866 my ($result) = $sth->fetchrow;
868 $cardnumber = $result + 1;
876 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
877 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
878 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
880 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
881 with children) and looks up the borrowers who are guaranteed by that
882 borrower (i.e., the patron's children).
884 C<&GetGuarantees> returns two values: an integer giving the number of
885 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
886 of references to hash, which gives the actual results.
892 my ($borrowernumber) = @_;
893 my $dbh = C4::Context->dbh;
896 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
898 $sth->execute($borrowernumber);
901 my $data = $sth->fetchall_arrayref({});
903 return ( scalar(@$data), $data );
906 =head2 UpdateGuarantees
908 &UpdateGuarantees($parent_borrno);
911 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
912 with the modified information
917 sub UpdateGuarantees {
919 my $dbh = C4::Context->dbh;
920 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
921 for ( my $i = 0 ; $i < $count ; $i++ ) {
924 # It looks like the $i is only being returned to handle walking through
925 # the array, which is probably better done as a foreach loop.
927 my $guaquery = qq|UPDATE borrowers
928 SET address='$data{'address'}',fax='$data{'fax'}',
929 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
930 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
932 my $sth3 = $dbh->prepare($guaquery);
937 =head2 GetPendingIssues
939 ($count, $issues) = &GetPendingIssues($borrowernumber);
941 Looks up what the patron with the given borrowernumber has borrowed.
943 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
944 reference-to-array, where each element is a reference-to-hash; the
945 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
946 in the Koha database. C<$count> is the number of elements in
952 sub GetPendingIssues {
953 my ($borrowernumber) = @_;
954 my $dbh = C4::Context->dbh;
956 my $sth = $dbh->prepare(
957 "SELECT * FROM issues
958 LEFT JOIN items ON issues.itemnumber=items.itemnumber
959 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
960 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
963 ORDER BY issues.issuedate"
965 $sth->execute($borrowernumber);
966 my $data = $sth->fetchall_arrayref({});
967 my $today = POSIX::strftime("%Y%m%d", localtime);
969 my $datedue = $_->{'date_due'};
971 if ( $datedue < $today ) {
976 return ( scalar(@$data), $data );
981 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
983 Looks up what the patron with the given borrowernumber has borrowed,
984 and sorts the results.
986 C<$sortkey> is the name of a field on which to sort the results. This
987 should be the name of a field in the C<issues>, C<biblio>,
988 C<biblioitems>, or C<items> table in the Koha database.
990 C<$limit> is the maximum number of results to return.
992 C<&GetAllIssues> returns a two-element array. C<$issues> is a
993 reference-to-array, where each element is a reference-to-hash; the
994 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
995 C<items> tables of the Koha database. C<$count> is the number of
996 elements in C<$issues>
1002 my ( $borrowernumber, $order, $limit ) = @_;
1004 #FIXME: sanity-check order and limit
1005 my $dbh = C4::Context->dbh;
1008 "SELECT *,items.timestamp AS itemstimestamp
1010 LEFT JOIN items on items.itemnumber=issues.itemnumber
1011 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1012 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1013 WHERE borrowernumber=?
1015 SELECT *,items.timestamp AS itemstimestamp
1017 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1018 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1019 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1020 WHERE borrowernumber=?
1022 if ( $limit != 0 ) {
1023 $query .= " limit $limit";
1027 my $sth = $dbh->prepare($query);
1028 $sth->execute($borrowernumber, $borrowernumber);
1031 while ( my $data = $sth->fetchrow_hashref ) {
1032 $result[$i] = $data;
1037 # get all issued items for borrowernumber from oldissues table
1038 # large chunk of older issues data put into table oldissues
1039 # to speed up db calls for issuing items
1040 if ( C4::Context->preference("ReadingHistory") ) {
1041 # FIXME oldissues (not to be confused with old_issues) is
1042 # apparently specific to HLT. Not sure if the ReadingHistory
1043 # syspref is still required, as old_issues by design
1044 # is no longer checked with each loan.
1045 my $query2 = "SELECT * FROM oldissues
1046 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1047 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1048 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1049 WHERE borrowernumber=?
1051 if ( $limit != 0 ) {
1052 $limit = $limit - $count;
1053 $query2 .= " limit $limit";
1056 my $sth2 = $dbh->prepare($query2);
1057 $sth2->execute($borrowernumber);
1059 while ( my $data2 = $sth2->fetchrow_hashref ) {
1060 $result[$i] = $data2;
1067 return ( $i, \@result );
1071 =head2 GetMemberAccountRecords
1073 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1075 Looks up accounting data for the patron with the given borrowernumber.
1077 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1078 reference-to-array, where each element is a reference-to-hash; the
1079 keys are the fields of the C<accountlines> table in the Koha database.
1080 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1081 total amount outstanding for all of the account lines.
1086 sub GetMemberAccountRecords {
1087 my ($borrowernumber,$date) = @_;
1088 my $dbh = C4::Context->dbh;
1094 WHERE borrowernumber=?);
1095 my @bind = ($borrowernumber);
1096 if ($date && $date ne ''){
1097 $strsth.=" AND date < ? ";
1100 $strsth.=" ORDER BY date desc,timestamp DESC";
1101 my $sth= $dbh->prepare( $strsth );
1102 $sth->execute( @bind );
1104 while ( my $data = $sth->fetchrow_hashref ) {
1105 $acctlines[$numlines] = $data;
1107 $total += $data->{'amountoutstanding'};
1110 return ( $total, \@acctlines,$numlines);
1113 =head2 GetBorNotifyAcctRecord
1115 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1117 Looks up accounting data for the patron with the given borrowernumber per file number.
1119 (FIXME - I'm not at all sure what this is about.)
1121 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1122 reference-to-array, where each element is a reference-to-hash; the
1123 keys are the fields of the C<accountlines> table in the Koha database.
1124 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1125 total amount outstanding for all of the account lines.
1129 sub GetBorNotifyAcctRecord {
1130 my ( $borrowernumber, $notifyid ) = @_;
1131 my $dbh = C4::Context->dbh;
1134 my $sth = $dbh->prepare(
1137 WHERE borrowernumber=?
1139 AND amountoutstanding != '0'
1140 ORDER BY notify_id,accounttype
1142 # 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')
1144 $sth->execute( $borrowernumber, $notifyid );
1146 while ( my $data = $sth->fetchrow_hashref ) {
1147 $acctlines[$numlines] = $data;
1149 $total += $data->{'amountoutstanding'};
1152 return ( $total, \@acctlines, $numlines );
1155 =head2 checkuniquemember (OUEST-PROVENCE)
1157 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1159 Checks that a member exists or not in the database.
1161 C<&result> is nonzero (=exist) or 0 (=does not exist)
1162 C<&categorycode> is from categorycode table
1163 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1164 C<&surname> is the surname
1165 C<&firstname> is the firstname (only if collectivity=0)
1166 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1170 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1171 # This is especially true since first name is not even a required field.
1173 sub checkuniquemember {
1174 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1175 my $dbh = C4::Context->dbh;
1176 my $request = ($collectivity) ?
1177 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1178 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1179 my $sth = $dbh->prepare($request);
1180 if ($collectivity) {
1181 $sth->execute( uc($surname) );
1183 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1185 my @data = $sth->fetchrow;
1187 ( $data[0] ) and return $data[0], $data[1];
1191 sub checkcardnumber {
1192 my ($cardnumber,$borrowernumber) = @_;
1193 my $dbh = C4::Context->dbh;
1194 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1195 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1196 my $sth = $dbh->prepare($query);
1197 if ($borrowernumber) {
1198 $sth->execute($cardnumber,$borrowernumber);
1200 $sth->execute($cardnumber);
1202 if (my $data= $sth->fetchrow_hashref()){
1212 =head2 getzipnamecity (OUEST-PROVENCE)
1214 take all info from table city for the fields city and zip
1215 check for the name and the zip code of the city selected
1219 sub getzipnamecity {
1221 my $dbh = C4::Context->dbh;
1224 "select city_name,city_zipcode from cities where cityid=? ");
1225 $sth->execute($cityid);
1226 my @data = $sth->fetchrow;
1227 return $data[0], $data[1];
1231 =head2 getdcity (OUEST-PROVENCE)
1233 recover cityid with city_name condition
1238 my ($city_name) = @_;
1239 my $dbh = C4::Context->dbh;
1240 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1241 $sth->execute($city_name);
1242 my $data = $sth->fetchrow;
1247 =head2 GetExpiryDate
1249 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1251 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1252 Return date is also in ISO format.
1257 my ( $categorycode, $dateenrolled ) = @_;
1258 my $enrolmentperiod = 12; # reasonable default
1259 if ($categorycode) {
1260 my $dbh = C4::Context->dbh;
1261 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1262 $sth->execute($categorycode);
1263 $enrolmentperiod = $sth->fetchrow;
1265 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1266 my @date = split /-/,$dateenrolled;
1267 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1270 =head2 checkuserpassword (OUEST-PROVENCE)
1272 check for the password and login are not used
1273 return the number of record
1274 0=> NOT USED 1=> USED
1278 sub checkuserpassword {
1279 my ( $borrowernumber, $userid, $password ) = @_;
1280 $password = md5_base64($password);
1281 my $dbh = C4::Context->dbh;
1284 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1286 $sth->execute( $borrowernumber, $userid, $password );
1287 my $number_rows = $sth->fetchrow;
1288 return $number_rows;
1292 =head2 GetborCatFromCatType
1294 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1296 Looks up the different types of borrowers in the database. Returns two
1297 elements: a reference-to-array, which lists the borrower category
1298 codes, and a reference-to-hash, which maps the borrower category codes
1299 to category descriptions.
1304 sub GetborCatFromCatType {
1305 my ( $category_type, $action ) = @_;
1306 my $dbh = C4::Context->dbh;
1307 my $request = qq| SELECT categorycode,description
1310 ORDER BY categorycode|;
1311 my $sth = $dbh->prepare($request);
1313 $sth->execute($category_type);
1322 while ( my $data = $sth->fetchrow_hashref ) {
1323 push @codes, $data->{'categorycode'};
1324 $labels{ $data->{'categorycode'} } = $data->{'description'};
1327 return ( \@codes, \%labels );
1330 =head2 GetBorrowercategory
1332 $hashref = &GetBorrowercategory($categorycode);
1334 Given the borrower's category code, the function returns the corresponding
1335 data hashref for a comprehensive information display.
1339 sub GetBorrowercategory {
1341 my $dbh = C4::Context->dbh;
1344 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1346 WHERE categorycode = ?"
1348 $sth->execute($catcode);
1350 $sth->fetchrow_hashref;
1353 } # sub getborrowercategory
1355 =head2 ethnicitycategories
1357 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1359 Looks up the different ethnic types in the database. Returns two
1360 elements: a reference-to-array, which lists the ethnicity codes, and a
1361 reference-to-hash, which maps the ethnicity codes to ethnicity
1368 sub ethnicitycategories {
1369 my $dbh = C4::Context->dbh;
1370 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1374 while ( my $data = $sth->fetchrow_hashref ) {
1375 push @codes, $data->{'code'};
1376 $labels{ $data->{'code'} } = $data->{'name'};
1379 return ( \@codes, \%labels );
1384 $ethn_name = &fixEthnicity($ethn_code);
1386 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1387 corresponding descriptive name from the C<ethnicity> table in the
1388 Koha database ("European" or "Pacific Islander").
1395 my $ethnicity = shift;
1396 return unless $ethnicity;
1397 my $dbh = C4::Context->dbh;
1398 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1399 $sth->execute($ethnicity);
1400 my $data = $sth->fetchrow_hashref;
1402 return $data->{'name'};
1403 } # sub fixEthnicity
1407 $dateofbirth,$date = &GetAge($date);
1409 this function return the borrowers age with the value of dateofbirth
1415 my ( $date, $date_ref ) = @_;
1417 if ( not defined $date_ref ) {
1418 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1421 my ( $year1, $month1, $day1 ) = split /-/, $date;
1422 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1424 my $age = $year2 - $year1;
1425 if ( $month1 . $day1 > $month2 . $day2 ) {
1432 =head2 get_institutions
1433 $insitutions = get_institutions();
1435 Just returns a list of all the borrowers of type I, borrownumber and name
1440 sub get_institutions {
1441 my $dbh = C4::Context->dbh();
1444 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1448 while ( my $data = $sth->fetchrow_hashref() ) {
1449 $orgs{ $data->{'borrowernumber'} } = $data;
1454 } # sub get_institutions
1456 =head2 add_member_orgs
1458 add_member_orgs($borrowernumber,$borrowernumbers);
1460 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1465 sub add_member_orgs {
1466 my ( $borrowernumber, $otherborrowers ) = @_;
1467 my $dbh = C4::Context->dbh();
1469 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1470 my $sth = $dbh->prepare($query);
1471 foreach my $otherborrowernumber (@$otherborrowers) {
1472 $sth->execute( $borrowernumber, $otherborrowernumber );
1476 } # sub add_member_orgs
1478 =head2 GetCities (OUEST-PROVENCE)
1480 ($id_cityarrayref, $city_hashref) = &GetCities();
1482 Looks up the different city and zip in the database. Returns two
1483 elements: a reference-to-array, which lists the zip city
1484 codes, and a reference-to-hash, which maps the name of the city.
1485 WHERE =>OUEST PROVENCE OR EXTERIEUR
1491 #my ($type_city) = @_;
1492 my $dbh = C4::Context->dbh;
1493 my $query = qq|SELECT cityid,city_zipcode,city_name
1495 ORDER BY city_name|;
1496 my $sth = $dbh->prepare($query);
1498 #$sth->execute($type_city);
1502 # insert empty value to create a empty choice in cgi popup
1505 while ( my $data = $sth->fetchrow_hashref ) {
1506 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1507 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1510 #test to know if the table contain some records if no the function return nothing
1514 # all we have is the one blank row
1519 return ( \@id, \%city );
1523 =head2 GetSortDetails (OUEST-PROVENCE)
1525 ($lib) = &GetSortDetails($category,$sortvalue);
1527 Returns the authorized value details
1528 C<&$lib>return value of authorized value details
1529 C<&$sortvalue>this is the value of authorized value
1530 C<&$category>this is the value of authorized value category
1534 sub GetSortDetails {
1535 my ( $category, $sortvalue ) = @_;
1536 my $dbh = C4::Context->dbh;
1537 my $query = qq|SELECT lib
1538 FROM authorised_values
1540 AND authorised_value=? |;
1541 my $sth = $dbh->prepare($query);
1542 $sth->execute( $category, $sortvalue );
1543 my $lib = $sth->fetchrow;
1544 return ($lib) if ($lib);
1545 return ($sortvalue) unless ($lib);
1548 =head2 DeleteBorrower
1550 () = &DeleteBorrower($member);
1552 delete all data fo borrowers and add record to deletedborrowers table
1553 C<&$member>this is the borrowernumber
1557 sub MoveMemberToDeleted {
1559 my $dbh = C4::Context->dbh;
1561 $query = qq|SELECT *
1563 WHERE borrowernumber=?|;
1564 my $sth = $dbh->prepare($query);
1565 $sth->execute($member);
1566 my @data = $sth->fetchrow_array;
1569 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1570 . ( "?," x ( scalar(@data) - 1 ) )
1572 $sth->execute(@data);
1578 DelMember($borrowernumber);
1580 This function remove directly a borrower whitout writing it on deleteborrower.
1581 + Deletes reserves for the borrower
1586 my $dbh = C4::Context->dbh;
1587 my $borrowernumber = shift;
1588 #warn "in delmember with $borrowernumber";
1589 return unless $borrowernumber; # borrowernumber is mandatory.
1591 my $query = qq|DELETE
1593 WHERE borrowernumber=?|;
1594 my $sth = $dbh->prepare($query);
1595 $sth->execute($borrowernumber);
1600 WHERE borrowernumber = ?
1602 $sth = $dbh->prepare($query);
1603 $sth->execute($borrowernumber);
1605 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1609 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1611 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1613 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1618 sub ExtendMemberSubscriptionTo {
1619 my ( $borrowerid,$date) = @_;
1620 my $dbh = C4::Context->dbh;
1621 my $borrower = GetMember($borrowerid,'borrowernumber');
1623 $date=POSIX::strftime("%Y-%m-%d",localtime());
1624 my $borrower = GetMember($borrowerid,'borrowernumber');
1625 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1627 my $sth = $dbh->do(<<EOF);
1629 SET dateexpiry='$date'
1630 WHERE borrowernumber='$borrowerid'
1632 # add enrolmentfee if needed
1633 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1634 $sth->execute($borrower->{'categorycode'});
1635 my ($enrolmentfee) = $sth->fetchrow;
1636 if ($enrolmentfee) {
1637 # insert fee in patron debts
1638 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1640 return $date if ($sth);
1644 =head2 GetRoadTypes (OUEST-PROVENCE)
1646 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1648 Looks up the different road type . Returns two
1649 elements: a reference-to-array, which lists the id_roadtype
1650 codes, and a reference-to-hash, which maps the road type of the road .
1655 my $dbh = C4::Context->dbh;
1657 SELECT roadtypeid,road_type
1659 ORDER BY road_type|;
1660 my $sth = $dbh->prepare($query);
1665 # insert empty value to create a empty choice in cgi popup
1667 while ( my $data = $sth->fetchrow_hashref ) {
1669 push @id, $data->{'roadtypeid'};
1670 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1673 #test to know if the table contain some records if no the function return nothing
1681 return ( \@id, \%roadtype );
1687 =head2 GetTitles (OUEST-PROVENCE)
1689 ($borrowertitle)= &GetTitles();
1691 Looks up the different title . Returns array with all borrowers title
1696 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1697 unshift( @borrowerTitle, "" );
1698 my $count=@borrowerTitle;
1703 return ( \@borrowerTitle);
1707 =head2 GetPatronImage
1709 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1711 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1715 sub GetPatronImage {
1716 my ($cardnumber) = @_;
1717 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1718 my $dbh = C4::Context->dbh;
1719 my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1720 my $sth = $dbh->prepare($query);
1721 $sth->execute($cardnumber);
1722 my $imagedata = $sth->fetchrow_hashref;
1723 my $dberror = $sth->errstr;
1724 warn "Database error!" if $sth->errstr;
1726 return $imagedata, $dberror;
1729 =head2 PutPatronImage
1731 PutPatronImage($cardnumber, $mimetype, $imgfile);
1733 Stores patron binary image data and mimetype in database.
1734 NOTE: This function is good for updating images as well as inserting new images in the database.
1738 sub PutPatronImage {
1739 my ($cardnumber, $mimetype, $imgfile) = @_;
1740 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1741 my $dbh = C4::Context->dbh;
1742 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1743 my $sth = $dbh->prepare($query);
1744 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1745 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1746 my $dberror = $sth->errstr;
1751 =head2 RmPatronImage
1753 my ($dberror) = RmPatronImage($cardnumber);
1755 Removes the image for the patron with the supplied cardnumber.
1760 my ($cardnumber) = @_;
1761 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1762 my $dbh = C4::Context->dbh;
1763 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1764 my $sth = $dbh->prepare($query);
1765 $sth->execute($cardnumber);
1766 my $dberror = $sth->errstr;
1767 warn "Database error!" if $sth->errstr;
1772 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1774 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1776 Returns the description of roadtype
1777 C<&$roadtype>return description of road type
1778 C<&$roadtypeid>this is the value of roadtype s
1782 sub GetRoadTypeDetails {
1783 my ($roadtypeid) = @_;
1784 my $dbh = C4::Context->dbh;
1788 WHERE roadtypeid=?|;
1789 my $sth = $dbh->prepare($query);
1790 $sth->execute($roadtypeid);
1791 my $roadtype = $sth->fetchrow;
1795 =head2 GetBorrowersWhoHaveNotBorrowedSince
1797 &GetBorrowersWhoHaveNotBorrowedSince($date)
1799 this function get all borrowers who haven't borrowed since the date given on input arg.
1803 sub GetBorrowersWhoHaveNotBorrowedSince {
1804 ### 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.
1806 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1807 my $filterbranch = shift ||
1808 ((C4::Context->preference('IndependantBranches')
1809 && C4::Context->userenv
1810 && C4::Context->userenv->{flags}!=1
1811 && C4::Context->userenv->{branch})
1812 ? C4::Context->userenv->{branch}
1814 my $dbh = C4::Context->dbh;
1816 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1818 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1821 if ($filterbranch && $filterbranch ne ""){
1822 $query.=" WHERE branchcode= ?";
1823 push @query_params,$filterbranch;
1825 $query.=" GROUP BY borrowers.borrowernumber";
1827 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1828 push @query_params,$filterdate;
1831 my $sth = $dbh->prepare($query);
1832 if (scalar(@query_params)>0){
1833 $sth->execute(@query_params);
1840 while ( my $data = $sth->fetchrow_hashref ) {
1841 push @results, $data;
1846 =head2 GetBorrowersWhoHaveNeverBorrowed
1848 $results = &GetBorrowersWhoHaveNeverBorrowed
1850 this function get all borrowers who have never borrowed.
1852 I<$result> is a ref to an array which all elements are a hasref.
1856 sub GetBorrowersWhoHaveNeverBorrowed {
1857 my $filterbranch = shift ||
1858 ((C4::Context->preference('IndependantBranches')
1859 && C4::Context->userenv
1860 && C4::Context->userenv->{flags}!=1
1861 && C4::Context->userenv->{branch})
1862 ? C4::Context->userenv->{branch}
1864 my $dbh = C4::Context->dbh;
1866 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1868 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1869 WHERE issues.borrowernumber IS NULL
1872 if ($filterbranch && $filterbranch ne ""){
1873 $query.=" AND branchcode= ?";
1874 push @query_params,$filterbranch;
1878 my $sth = $dbh->prepare($query);
1879 if (scalar(@query_params)>0){
1880 $sth->execute(@query_params);
1887 while ( my $data = $sth->fetchrow_hashref ) {
1888 push @results, $data;
1893 =head2 GetBorrowersWithIssuesHistoryOlderThan
1895 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1897 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1899 I<$result> is a ref to an array which all elements are a hashref.
1900 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1904 sub GetBorrowersWithIssuesHistoryOlderThan {
1905 my $dbh = C4::Context->dbh;
1906 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1907 my $filterbranch = shift ||
1908 ((C4::Context->preference('IndependantBranches')
1909 && C4::Context->userenv
1910 && C4::Context->userenv->{flags}!=1
1911 && C4::Context->userenv->{branch})
1912 ? C4::Context->userenv->{branch}
1915 SELECT count(borrowernumber) as n,borrowernumber
1917 WHERE returndate < ?
1918 AND borrowernumber IS NOT NULL
1921 $query.=" AND branchcode=\'$filterbranch\'";
1923 $query.=" GROUP BY borrowernumber ";
1925 my $sth = $dbh->prepare($query);
1926 $sth->execute($date);
1929 while ( my $data = $sth->fetchrow_hashref ) {
1930 push @results, $data;
1935 =head2 GetBorrowersNamesAndLatestIssue
1937 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1939 this function get borrowers Names and surnames and Issue information.
1941 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1942 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1946 sub GetBorrowersNamesAndLatestIssue {
1947 my $dbh = C4::Context->dbh;
1948 my @borrowernumbers=@_;
1950 SELECT surname,lastname, phone, email,max(timestamp)
1952 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1953 GROUP BY borrowernumber
1955 my $sth = $dbh->prepare($query);
1957 my $results = $sth->fetchall_arrayref({});
1960 END { } # module clean-up code here (global destructor)