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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
32 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
34 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
38 $debug = $ENV{DEBUG} || 0;
50 &GetMemberIssuesAndFines
70 &GetMemberAccountRecords
71 &GetBorNotifyAcctRecord
75 &GetBorrowercategoryList
77 &GetBorrowersWhoHaveNotBorrowedSince
78 &GetBorrowersWhoHaveNeverBorrowed
79 &GetBorrowersWithIssuesHistoryOlderThan
105 &ExtendMemberSubscriptionTo
123 C4::Members - Perl Module containing convenience functions for member handling
131 This module contains routines for adding, modifying and deleting members/patrons/borrowers
139 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
143 Looks up patrons (borrowers) by name.
145 BUGFIX 499: C<$type> is now used to determine type of search.
146 if $type is "simple", search is performed on the first letter of the
149 $category_type is used to get a specified type of user.
150 (mainly adults when creating a child.)
152 C<$searchstring> is a space-separated list of search terms. Each term
153 must match the beginning a borrower's surname, first name, or other
156 C<$filter> is assumed to be a list of elements to filter results on
158 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
160 C<&SearchMember> returns a two-element list. C<$borrowers> is a
161 reference-to-array; each element is a reference-to-hash, whose keys
162 are the fields of the C<borrowers> table in the Koha database.
163 C<$count> is the number of elements in C<$borrowers>.
168 #used by member enquiries from the intranet
170 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
171 my $dbh = C4::Context->dbh;
177 # this is used by circulation everytime a new borrowers cardnumber is scanned
178 # so we can check an exact match first, if that works return, otherwise do the rest
179 $query = "SELECT * FROM borrowers
180 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
182 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
183 $sth->execute($searchstring);
184 my $data = $sth->fetchall_arrayref({});
186 return ( scalar(@$data), $data );
189 if ( $type eq "simple" ) # simple search for one letter only
191 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
192 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
193 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
194 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
195 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
198 $query.=" ORDER BY $orderby";
199 @bind = ("$searchstring%","$searchstring");
201 else # advanced search looking in surname, firstname and othernames
203 @data = split( ' ', $searchstring );
206 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
207 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
208 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
211 $query.="((surname LIKE ? OR surname LIKE ?
212 OR firstname LIKE ? OR firstname LIKE ?
213 OR othernames LIKE ? OR othernames LIKE ?)
215 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
217 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
218 "$data[0]%", "% $data[0]%"
220 for ( my $i = 1 ; $i < $count ; $i++ ) {
221 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
222 OR firstname LIKE ? OR firstname LIKE ?
223 OR othernames LIKE ? OR othernames LIKE ?)";
225 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
226 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
230 $query = $query . ") OR cardnumber LIKE ? ";
231 push( @bind, $searchstring );
232 $query .= "order by $orderby";
237 $sth = $dbh->prepare($query);
239 $debug and print STDERR "Q $orderby : $query\n";
240 $sth->execute(@bind);
242 $data = $sth->fetchall_arrayref({});
244 return ( scalar(@$data), $data );
251 $borrowers_result_array_ref = &Search($filter,$orderby, $limit, $columns_out, $search_on_fields,$searchtype);
255 Looks up patrons (borrowers) on filter.
257 BUGFIX 499: C<$type> is now used to determine type of search.
258 if $type is "simple", search is performed on the first letter of the
261 $category_type is used to get a specified type of user.
262 (mainly adults when creating a child.)
265 - a space-separated list of search terms. Implicit AND is done on them
266 - a hash ref containing fieldnames associated with queried value
267 - an array ref combining the two previous elements Implicit OR is done between each array element
270 C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending
272 C<$limit> is there to allow limiting number of results returned
274 C<&columns_out> is an array ref to the fieldnames you want to see in the result list
276 C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search
278 C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed
283 my ($filter,$orderby, $limit, $columns_out, $search_on_fields,$searchtype) = @_;
285 if (ref($filter) eq "ARRAY"){
286 push @filters,@$filter;
289 push @filters,$filter;
291 if (C4::Context->preference('ExtendedPatronAttributes')) {
292 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
293 push @filters,@$matching_records;
295 $searchtype||="start_with";
296 my $data=SearchInTable("borrowers",\@filters,$orderby,$limit,$columns_out,$search_on_fields,$searchtype);
301 =head2 GetMemberDetails
303 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
305 Looks up a patron and returns information about him or her. If
306 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
307 up the borrower by number; otherwise, it looks up the borrower by card
310 C<$borrower> is a reference-to-hash whose keys are the fields of the
311 borrowers table in the Koha database. In addition,
312 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
313 about the patron. Its keys act as flags :
315 if $borrower->{flags}->{LOST} {
316 # Patron's card was reported lost
319 If the state of a flag means that the patron should not be
320 allowed to borrow any more books, then it will have a C<noissues> key
323 See patronflags for more details.
325 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
326 about the top-level permissions flags set for the borrower. For example,
327 if a user has the "editcatalogue" permission,
328 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
333 sub GetMemberDetails {
334 my ( $borrowernumber, $cardnumber ) = @_;
335 my $dbh = C4::Context->dbh;
338 if ($borrowernumber) {
339 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
340 $sth->execute($borrowernumber);
342 elsif ($cardnumber) {
343 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
344 $sth->execute($cardnumber);
349 my $borrower = $sth->fetchrow_hashref;
350 my ($amount) = GetMemberAccountRecords( $borrowernumber);
351 $borrower->{'amountoutstanding'} = $amount;
352 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
353 my $flags = patronflags( $borrower);
356 $sth = $dbh->prepare("select bit,flag from userflags");
358 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
359 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
360 $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);
378 $flags = &patronflags($patron);
380 This function is not exported.
382 The following will be set where applicable:
383 $flags->{CHARGES}->{amount} Amount of debt
384 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
385 $flags->{CHARGES}->{message} Message -- deprecated
387 $flags->{CREDITS}->{amount} Amount of credit
388 $flags->{CREDITS}->{message} Message -- deprecated
390 $flags->{ GNA } Patron has no valid address
391 $flags->{ GNA }->{noissues} Set for each GNA
392 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
394 $flags->{ LOST } Patron's card reported lost
395 $flags->{ LOST }->{noissues} Set for each LOST
396 $flags->{ LOST }->{message} Message -- deprecated
398 $flags->{DBARRED} Set if patron debarred, no access
399 $flags->{DBARRED}->{noissues} Set for each DBARRED
400 $flags->{DBARRED}->{message} Message -- deprecated
403 $flags->{ NOTES }->{message} The note itself. NOT deprecated
405 $flags->{ ODUES } Set if patron has overdue books.
406 $flags->{ ODUES }->{message} "Yes" -- deprecated
407 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
408 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
410 $flags->{WAITING} Set if any of patron's reserves are available
411 $flags->{WAITING}->{message} Message -- deprecated
412 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
416 C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
417 overdue items. Its elements are references-to-hash, each describing an
418 overdue item. The keys are selected fields from the issues, biblio,
419 biblioitems, and items tables of the Koha database.
421 C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
422 the overdue items, one per line. Deprecated.
424 C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
425 available items. Each element is a reference-to-hash whose keys are
426 fields from the reserves table of the Koha database.
430 All the "message" fields that include language generated in this function are deprecated,
431 because such strings belong properly in the display layer.
433 The "message" field that comes from the DB is OK.
437 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
438 # FIXME rename this function.
441 my ( $patroninformation) = @_;
442 my $dbh=C4::Context->dbh;
443 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
446 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
447 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
448 $flaginfo{'amount'} = sprintf "%.02f", $amount;
449 if ( $amount > $noissuescharge ) {
450 $flaginfo{'noissues'} = 1;
452 $flags{'CHARGES'} = \%flaginfo;
454 elsif ( $amount < 0 ) {
456 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
457 $flaginfo{'amount'} = sprintf "%.02f", $amount;
458 $flags{'CREDITS'} = \%flaginfo;
460 if ( $patroninformation->{'gonenoaddress'}
461 && $patroninformation->{'gonenoaddress'} == 1 )
464 $flaginfo{'message'} = 'Borrower has no valid address.';
465 $flaginfo{'noissues'} = 1;
466 $flags{'GNA'} = \%flaginfo;
468 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
470 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
471 $flaginfo{'noissues'} = 1;
472 $flags{'LOST'} = \%flaginfo;
474 if ( $patroninformation->{'debarred'}
475 && $patroninformation->{'debarred'} == 1 )
478 $flaginfo{'message'} = 'Borrower is Debarred.';
479 $flaginfo{'noissues'} = 1;
480 $flags{'DBARRED'} = \%flaginfo;
482 if ( $patroninformation->{'borrowernotes'}
483 && $patroninformation->{'borrowernotes'} )
486 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
487 $flags{'NOTES'} = \%flaginfo;
489 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
492 $flaginfo{'message'} = "Yes";
493 $flaginfo{'itemlist'} = $itemsoverdue;
494 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
497 $flaginfo{'itemlisttext'} .=
498 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
500 $flags{'ODUES'} = \%flaginfo;
502 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
503 my $nowaiting = scalar @itemswaiting;
504 if ( $nowaiting > 0 ) {
506 $flaginfo{'message'} = "Reserved items available";
507 $flaginfo{'itemlist'} = \@itemswaiting;
508 $flags{'WAITING'} = \%flaginfo;
516 $borrower = &GetMember(%information);
518 Retrieve the first patron record meeting on criteria listed in the
519 C<%information> hash, which should contain one or more
520 pairs of borrowers column names and values, e.g.,
522 $borrower = GetMember(borrowernumber => id);
524 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
525 the C<borrowers> table in the Koha database.
527 FIXME: GetMember() is used throughout the code as a lookup
528 on a unique key such as the borrowernumber, but this meaning is not
529 enforced in the routine itself.
535 my ( %information ) = @_;
536 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
537 #passing mysql's kohaadmin?? Makes no sense as a query
540 my $dbh = C4::Context->dbh;
542 q{SELECT borrowers.*, categories.category_type, categories.description
544 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
547 for (keys %information ) {
555 if (defined $information{$_}) {
557 push @values, $information{$_};
560 $select .= "$_ IS NULL";
563 $debug && warn $select, " ",values %information;
564 my $sth = $dbh->prepare("$select");
565 $sth->execute(map{$information{$_}} keys %information);
566 my $data = $sth->fetchall_arrayref({});
567 #FIXME interface to this routine now allows generation of a result set
568 #so whole array should be returned but bowhere in the current code expects this
577 =head2 IsMemberBlocked
581 my $blocked = IsMemberBlocked( $borrowernumber );
583 return the status, and the number of day or documents, depends his punishment
586 -1 if the user have overdue returns
587 1 if the user is punished X days
588 0 if the user is authorised to loan
594 sub IsMemberBlocked {
595 my $borrowernumber = shift;
596 my $dbh = C4::Context->dbh;
597 # if he have late issues
598 my $sth = $dbh->prepare(
599 "SELECT COUNT(*) as latedocs
601 WHERE borrowernumber = ?
602 AND date_due < now()"
604 $sth->execute($borrowernumber);
605 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
607 return (-1, $latedocs) if $latedocs > 0;
611 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
612 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
615 # or if he must wait to loan
616 if(C4::Context->preference("item-level_itypes")){
618 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
619 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
622 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
623 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
624 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
627 qq{ WHERE finedays IS NOT NULL
628 AND date_due < returndate
629 AND borrowernumber = ?
630 ORDER BY blockingdate DESC, blockedcount DESC
632 $sth=$dbh->prepare($strsth);
633 $sth->execute($borrowernumber);
634 my $row = $sth->fetchrow_hashref;
635 my $blockeddate = $row->{'blockeddate'};
636 my $blockedcount = $row->{'blockedcount'};
638 return (1, $blockedcount) if $blockedcount > 0;
643 =head2 GetMemberIssuesAndFines
645 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
647 Returns aggregate data about items borrowed by the patron with the
648 given borrowernumber.
650 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
651 number of overdue items the patron currently has borrowed. C<$issue_count> is the
652 number of books the patron currently has borrowed. C<$total_fines> is
653 the total fine currently due by the borrower.
658 sub GetMemberIssuesAndFines {
659 my ( $borrowernumber ) = @_;
660 my $dbh = C4::Context->dbh;
661 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
663 $debug and warn $query."\n";
664 my $sth = $dbh->prepare($query);
665 $sth->execute($borrowernumber);
666 my $issue_count = $sth->fetchrow_arrayref->[0];
668 $sth = $dbh->prepare(
669 "SELECT COUNT(*) FROM issues
670 WHERE borrowernumber = ?
671 AND date_due < now()"
673 $sth->execute($borrowernumber);
674 my $overdue_count = $sth->fetchrow_arrayref->[0];
676 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
677 $sth->execute($borrowernumber);
678 my $total_fines = $sth->fetchrow_arrayref->[0];
680 return ($overdue_count, $issue_count, $total_fines);
684 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
693 my $success = ModMember(borrowernumber => $borrowernumber, [ field => value ]... );
695 Modify borrower's data. All date fields should ALREADY be in ISO format.
698 true on success, or false on failure
705 # test to know if you must update or not the borrower password
706 if (exists $data{password}) {
707 if ($data{password} eq '****' or $data{password} eq '') {
708 delete $data{password};
710 $data{password} = md5_base64($data{password});
713 my $execute_success=UpdateInTable("borrowers",\%data);
714 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
715 # so when we update information for an adult we should check for guarantees and update the relevant part
716 # of their records, ie addresses and phone numbers
717 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
718 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
719 # is adult check guarantees;
720 UpdateGuarantees(%data);
722 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})")
723 if C4::Context->preference("BorrowersLog");
725 return $execute_success;
733 $borrowernumber = &AddMember(%borrower);
735 insert new borrower into table
736 Returns the borrowernumber
743 my $dbh = C4::Context->dbh;
744 $data{'password'} = '!' if (not $data{'password'} and $data{'userid'});
745 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
746 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
747 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
748 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
750 # check for enrollment fee & add it if needed
751 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
752 $sth->execute($data{'categorycode'});
753 my ($enrolmentfee) = $sth->fetchrow;
754 if ($enrolmentfee && $enrolmentfee > 0) {
755 # insert fee in patron debts
756 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
758 return $data{'borrowernumber'};
763 my ($uid,$member) = @_;
764 my $dbh = C4::Context->dbh;
765 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
766 # Then we need to tell the user and have them create a new one.
769 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
770 $sth->execute( $uid, $member );
771 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
779 sub Generate_Userid {
780 my ($borrowernumber, $firstname, $surname) = @_;
784 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
785 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
786 $newuid = lc("$firstname.$surname");
787 $newuid .= $offset unless $offset == 0;
790 } while (!Check_Userid($newuid,$borrowernumber));
796 my ( $uid, $member, $digest ) = @_;
797 my $dbh = C4::Context->dbh;
799 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
800 #Then we need to tell the user and have them create a new one.
804 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
805 $sth->execute( $uid, $member );
806 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
810 #Everything is good so we can update the information.
813 "update borrowers set userid=?, password=? where borrowernumber=?");
814 $sth->execute( $uid, $digest, $member );
818 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
824 =head2 fixup_cardnumber
826 Warning: The caller is responsible for locking the members table in write
827 mode, to avoid database corruption.
831 use vars qw( @weightings );
832 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
834 sub fixup_cardnumber ($) {
835 my ($cardnumber) = @_;
836 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
838 # Find out whether member numbers should be generated
839 # automatically. Should be either "1" or something else.
840 # Defaults to "0", which is interpreted as "no".
842 # if ($cardnumber !~ /\S/ && $autonumber_members) {
843 ($autonumber_members) or return $cardnumber;
844 my $checkdigit = C4::Context->preference('checkdigit');
845 my $dbh = C4::Context->dbh;
846 if ( $checkdigit and $checkdigit eq 'katipo' ) {
848 # if checkdigit is selected, calculate katipo-style cardnumber.
849 # otherwise, just use the max()
850 # purpose: generate checksum'd member numbers.
851 # We'll assume we just got the max value of digits 2-8 of member #'s
852 # from the database and our job is to increment that by one,
853 # determine the 1st and 9th digits and return the full string.
854 my $sth = $dbh->prepare(
855 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
858 my $data = $sth->fetchrow_hashref;
859 $cardnumber = $data->{new_num};
860 if ( !$cardnumber ) { # If DB has no values,
861 $cardnumber = 1000000; # start at 1000000
867 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
868 # read weightings, left to right, 1 char at a time
869 my $temp1 = $weightings[$i];
871 # sequence left to right, 1 char at a time
872 my $temp2 = substr( $cardnumber, $i, 1 );
874 # mult each char 1-7 by its corresponding weighting
875 $sum += $temp1 * $temp2;
878 my $rem = ( $sum % 11 );
879 $rem = 'X' if $rem == 10;
881 return "V$cardnumber$rem";
884 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
885 # better. I'll leave the original in in case it needs to be changed for you
886 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
887 my $sth = $dbh->prepare(
888 "select max(cast(cardnumber as signed)) from borrowers"
891 my ($result) = $sth->fetchrow;
894 return $cardnumber; # just here as a fallback/reminder
899 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
900 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
901 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
903 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
904 with children) and looks up the borrowers who are guaranteed by that
905 borrower (i.e., the patron's children).
907 C<&GetGuarantees> returns two values: an integer giving the number of
908 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
909 of references to hash, which gives the actual results.
915 my ($borrowernumber) = @_;
916 my $dbh = C4::Context->dbh;
919 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
921 $sth->execute($borrowernumber);
924 my $data = $sth->fetchall_arrayref({});
925 return ( scalar(@$data), $data );
928 =head2 UpdateGuarantees
930 &UpdateGuarantees($parent_borrno);
933 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
934 with the modified information
939 sub UpdateGuarantees {
941 my $dbh = C4::Context->dbh;
942 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
943 for ( my $i = 0 ; $i < $count ; $i++ ) {
946 # It looks like the $i is only being returned to handle walking through
947 # the array, which is probably better done as a foreach loop.
949 my $guaquery = qq|UPDATE borrowers
950 SET address='$data{'address'}',fax='$data{'fax'}',
951 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
952 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
954 my $sth3 = $dbh->prepare($guaquery);
958 =head2 GetPendingIssues
960 my $issues = &GetPendingIssues($borrowernumber);
962 Looks up what the patron with the given borrowernumber has borrowed.
964 C<&GetPendingIssues> returns a
965 reference-to-array where each element is a reference-to-hash; the
966 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
967 The keys include C<biblioitems> fields except marc and marcxml.
972 sub GetPendingIssues {
973 my ($borrowernumber) = @_;
974 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
975 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
976 # FIXME: circ/ciculation.pl tries to sort by timestamp!
977 # FIXME: C4::Print::printslip tries to sort by timestamp!
978 # FIXME: namespace collision: other collisions possible.
979 # FIXME: most of this data isn't really being used by callers.
980 my $sth = C4::Context->dbh->prepare(
986 biblioitems.itemtype,
989 biblioitems.publicationyear,
990 biblioitems.publishercode,
991 biblioitems.volumedate,
992 biblioitems.volumedesc,
995 issues.timestamp AS timestamp,
996 issues.renewals AS renewals,
997 items.renewals AS totalrenewals
999 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1000 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1001 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1004 ORDER BY issues.issuedate"
1006 $sth->execute($borrowernumber);
1007 my $data = $sth->fetchall_arrayref({});
1008 my $today = C4::Dates->new->output('iso');
1010 $_->{date_due} or next;
1011 ($_->{date_due} lt $today) and $_->{overdue} = 1;
1018 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1020 Looks up what the patron with the given borrowernumber has borrowed,
1021 and sorts the results.
1023 C<$sortkey> is the name of a field on which to sort the results. This
1024 should be the name of a field in the C<issues>, C<biblio>,
1025 C<biblioitems>, or C<items> table in the Koha database.
1027 C<$limit> is the maximum number of results to return.
1029 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1030 reference-to-array, where each element is a reference-to-hash; the
1031 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1032 C<items> tables of the Koha database. C<$count> is the number of
1033 elements in C<$issues>
1039 my ( $borrowernumber, $order, $limit ) = @_;
1041 #FIXME: sanity-check order and limit
1042 my $dbh = C4::Context->dbh;
1044 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1046 LEFT JOIN items on items.itemnumber=issues.itemnumber
1047 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1048 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1049 WHERE borrowernumber=?
1051 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1053 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1054 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1055 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1056 WHERE borrowernumber=?
1058 if ( $limit != 0 ) {
1059 $query .= " limit $limit";
1063 my $sth = $dbh->prepare($query);
1064 $sth->execute($borrowernumber, $borrowernumber);
1067 while ( my $data = $sth->fetchrow_hashref ) {
1068 push @result, $data;
1071 # get all issued items for borrowernumber from oldissues table
1072 # large chunk of older issues data put into table oldissues
1073 # to speed up db calls for issuing items
1074 if ( C4::Context->preference("ReadingHistory") ) {
1075 # FIXME oldissues (not to be confused with old_issues) is
1076 # apparently specific to HLT. Not sure if the ReadingHistory
1077 # syspref is still required, as old_issues by design
1078 # is no longer checked with each loan.
1079 my $query2 = "SELECT * FROM old_issues
1080 LEFT JOIN items ON items.itemnumber=old_issues.itemnumber
1081 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1082 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1083 WHERE borrowernumber=?
1085 if ( $limit != 0 ) {
1086 $limit = $limit - scalar(@result);
1087 $query2 .= " limit $limit";
1090 my $sth2 = $dbh->prepare($query2);
1091 $sth2->execute($borrowernumber);
1093 while ( my $data2 = $sth2->fetchrow_hashref ) {
1094 push @result, $data2;
1102 =head2 GetMemberAccountRecords
1104 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1106 Looks up accounting data for the patron with the given borrowernumber.
1108 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1109 reference-to-array, where each element is a reference-to-hash; the
1110 keys are the fields of the C<accountlines> table in the Koha database.
1111 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1112 total amount outstanding for all of the account lines.
1117 sub GetMemberAccountRecords {
1118 my ($borrowernumber,$date) = @_;
1119 my $dbh = C4::Context->dbh;
1125 WHERE borrowernumber=?);
1126 my @bind = ($borrowernumber);
1127 if ($date && $date ne ''){
1128 $strsth.=" AND date < ? ";
1131 $strsth.=" ORDER BY date desc,timestamp DESC";
1132 my $sth= $dbh->prepare( $strsth );
1133 $sth->execute( @bind );
1135 while ( my $data = $sth->fetchrow_hashref ) {
1136 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1137 $data->{biblionumber} = $biblio->{biblionumber};
1138 $data->{title} = $biblio->{title};
1139 $acctlines[$numlines] = $data;
1141 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1144 return ( $total, \@acctlines,$numlines);
1147 =head2 GetBorNotifyAcctRecord
1149 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1151 Looks up accounting data for the patron with the given borrowernumber per file number.
1153 (FIXME - I'm not at all sure what this is about.)
1155 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1156 reference-to-array, where each element is a reference-to-hash; the
1157 keys are the fields of the C<accountlines> table in the Koha database.
1158 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1159 total amount outstanding for all of the account lines.
1163 sub GetBorNotifyAcctRecord {
1164 my ( $borrowernumber, $notifyid ) = @_;
1165 my $dbh = C4::Context->dbh;
1168 my $sth = $dbh->prepare(
1171 WHERE borrowernumber=?
1173 AND amountoutstanding != '0'
1174 ORDER BY notify_id,accounttype
1176 # 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')
1178 $sth->execute( $borrowernumber, $notifyid );
1180 while ( my $data = $sth->fetchrow_hashref ) {
1181 $acctlines[$numlines] = $data;
1183 $total += int(100 * $data->{'amountoutstanding'});
1186 return ( $total, \@acctlines, $numlines );
1189 =head2 checkuniquemember (OUEST-PROVENCE)
1191 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1193 Checks that a member exists or not in the database.
1195 C<&result> is nonzero (=exist) or 0 (=does not exist)
1196 C<&categorycode> is from categorycode table
1197 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1198 C<&surname> is the surname
1199 C<&firstname> is the firstname (only if collectivity=0)
1200 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1204 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1205 # This is especially true since first name is not even a required field.
1207 sub checkuniquemember {
1208 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1209 my $dbh = C4::Context->dbh;
1210 my $request = ($collectivity) ?
1211 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1213 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1214 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1215 my $sth = $dbh->prepare($request);
1216 if ($collectivity) {
1217 $sth->execute( uc($surname) );
1218 } elsif($dateofbirth){
1219 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1221 $sth->execute( uc($surname), ucfirst($firstname));
1223 my @data = $sth->fetchrow;
1224 ( $data[0] ) and return $data[0], $data[1];
1228 sub checkcardnumber {
1229 my ($cardnumber,$borrowernumber) = @_;
1230 my $dbh = C4::Context->dbh;
1231 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1232 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1233 my $sth = $dbh->prepare($query);
1234 if ($borrowernumber) {
1235 $sth->execute($cardnumber,$borrowernumber);
1237 $sth->execute($cardnumber);
1239 if (my $data= $sth->fetchrow_hashref()){
1248 =head2 getzipnamecity (OUEST-PROVENCE)
1250 take all info from table city for the fields city and zip
1251 check for the name and the zip code of the city selected
1255 sub getzipnamecity {
1257 my $dbh = C4::Context->dbh;
1260 "select city_name,city_zipcode from cities where cityid=? ");
1261 $sth->execute($cityid);
1262 my @data = $sth->fetchrow;
1263 return $data[0], $data[1];
1267 =head2 getdcity (OUEST-PROVENCE)
1269 recover cityid with city_name condition
1274 my ($city_name) = @_;
1275 my $dbh = C4::Context->dbh;
1276 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1277 $sth->execute($city_name);
1278 my $data = $sth->fetchrow;
1283 =head2 GetExpiryDate
1285 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1287 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1288 Return date is also in ISO format.
1293 my ( $categorycode, $dateenrolled ) = @_;
1295 if ($categorycode) {
1296 my $dbh = C4::Context->dbh;
1297 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1298 $sth->execute($categorycode);
1299 $enrolments = $sth->fetchrow_hashref;
1301 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1302 my @date = split (/-/,$dateenrolled);
1303 if($enrolments->{enrolmentperiod}){
1304 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1306 return $enrolments->{enrolmentperioddate};
1310 =head2 checkuserpassword (OUEST-PROVENCE)
1312 check for the password and login are not used
1313 return the number of record
1314 0=> NOT USED 1=> USED
1318 sub checkuserpassword {
1319 my ( $borrowernumber, $userid, $password ) = @_;
1320 $password = md5_base64($password);
1321 my $dbh = C4::Context->dbh;
1324 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1326 $sth->execute( $borrowernumber, $userid, $password );
1327 my $number_rows = $sth->fetchrow;
1328 return $number_rows;
1332 =head2 GetborCatFromCatType
1334 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1336 Looks up the different types of borrowers in the database. Returns two
1337 elements: a reference-to-array, which lists the borrower category
1338 codes, and a reference-to-hash, which maps the borrower category codes
1339 to category descriptions.
1344 sub GetborCatFromCatType {
1345 my ( $category_type, $action ) = @_;
1346 # FIXME - This API seems both limited and dangerous.
1347 my $dbh = C4::Context->dbh;
1348 my $request = qq| SELECT categorycode,description
1351 ORDER BY categorycode|;
1352 my $sth = $dbh->prepare($request);
1354 $sth->execute($category_type);
1363 while ( my $data = $sth->fetchrow_hashref ) {
1364 push @codes, $data->{'categorycode'};
1365 $labels{ $data->{'categorycode'} } = $data->{'description'};
1367 return ( \@codes, \%labels );
1370 =head2 GetBorrowercategory
1372 $hashref = &GetBorrowercategory($categorycode);
1374 Given the borrower's category code, the function returns the corresponding
1375 data hashref for a comprehensive information display.
1377 $arrayref_hashref = &GetBorrowercategory;
1378 If no category code provided, the function returns all the categories.
1382 sub GetBorrowercategory {
1384 my $dbh = C4::Context->dbh;
1388 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1390 WHERE categorycode = ?"
1392 $sth->execute($catcode);
1394 $sth->fetchrow_hashref;
1398 } # sub getborrowercategory
1400 =head2 GetBorrowercategoryList
1402 $arrayref_hashref = &GetBorrowercategoryList;
1403 If no category code provided, the function returns all the categories.
1407 sub GetBorrowercategoryList {
1408 my $dbh = C4::Context->dbh;
1413 ORDER BY description"
1417 $sth->fetchall_arrayref({});
1419 } # sub getborrowercategory
1421 =head2 ethnicitycategories
1423 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1425 Looks up the different ethnic types in the database. Returns two
1426 elements: a reference-to-array, which lists the ethnicity codes, and a
1427 reference-to-hash, which maps the ethnicity codes to ethnicity
1434 sub ethnicitycategories {
1435 my $dbh = C4::Context->dbh;
1436 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1440 while ( my $data = $sth->fetchrow_hashref ) {
1441 push @codes, $data->{'code'};
1442 $labels{ $data->{'code'} } = $data->{'name'};
1444 return ( \@codes, \%labels );
1449 $ethn_name = &fixEthnicity($ethn_code);
1451 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1452 corresponding descriptive name from the C<ethnicity> table in the
1453 Koha database ("European" or "Pacific Islander").
1460 my $ethnicity = shift;
1461 return unless $ethnicity;
1462 my $dbh = C4::Context->dbh;
1463 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1464 $sth->execute($ethnicity);
1465 my $data = $sth->fetchrow_hashref;
1466 return $data->{'name'};
1467 } # sub fixEthnicity
1471 $dateofbirth,$date = &GetAge($date);
1473 this function return the borrowers age with the value of dateofbirth
1479 my ( $date, $date_ref ) = @_;
1481 if ( not defined $date_ref ) {
1482 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1485 my ( $year1, $month1, $day1 ) = split /-/, $date;
1486 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1488 my $age = $year2 - $year1;
1489 if ( $month1 . $day1 > $month2 . $day2 ) {
1496 =head2 get_institutions
1497 $insitutions = get_institutions();
1499 Just returns a list of all the borrowers of type I, borrownumber and name
1504 sub get_institutions {
1505 my $dbh = C4::Context->dbh();
1508 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1512 while ( my $data = $sth->fetchrow_hashref() ) {
1513 $orgs{ $data->{'borrowernumber'} } = $data;
1517 } # sub get_institutions
1519 =head2 add_member_orgs
1521 add_member_orgs($borrowernumber,$borrowernumbers);
1523 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1528 sub add_member_orgs {
1529 my ( $borrowernumber, $otherborrowers ) = @_;
1530 my $dbh = C4::Context->dbh();
1532 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1533 my $sth = $dbh->prepare($query);
1534 foreach my $otherborrowernumber (@$otherborrowers) {
1535 $sth->execute( $borrowernumber, $otherborrowernumber );
1538 } # sub add_member_orgs
1540 =head2 GetCities (OUEST-PROVENCE)
1542 ($id_cityarrayref, $city_hashref) = &GetCities();
1544 Looks up the different city and zip in the database. Returns two
1545 elements: a reference-to-array, which lists the zip city
1546 codes, and a reference-to-hash, which maps the name of the city.
1547 WHERE =>OUEST PROVENCE OR EXTERIEUR
1553 #my ($type_city) = @_;
1554 my $dbh = C4::Context->dbh;
1555 my $query = qq|SELECT cityid,city_zipcode,city_name
1557 ORDER BY city_name|;
1558 my $sth = $dbh->prepare($query);
1560 #$sth->execute($type_city);
1564 # insert empty value to create a empty choice in cgi popup
1567 while ( my $data = $sth->fetchrow_hashref ) {
1568 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1569 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1572 #test to know if the table contain some records if no the function return nothing
1575 # all we have is the one blank row
1580 return ( \@id, \%city );
1584 =head2 GetSortDetails (OUEST-PROVENCE)
1586 ($lib) = &GetSortDetails($category,$sortvalue);
1588 Returns the authorized value details
1589 C<&$lib>return value of authorized value details
1590 C<&$sortvalue>this is the value of authorized value
1591 C<&$category>this is the value of authorized value category
1595 sub GetSortDetails {
1596 my ( $category, $sortvalue ) = @_;
1597 my $dbh = C4::Context->dbh;
1598 my $query = qq|SELECT lib
1599 FROM authorised_values
1601 AND authorised_value=? |;
1602 my $sth = $dbh->prepare($query);
1603 $sth->execute( $category, $sortvalue );
1604 my $lib = $sth->fetchrow;
1605 return ($lib) if ($lib);
1606 return ($sortvalue) unless ($lib);
1609 =head2 MoveMemberToDeleted
1611 $result = &MoveMemberToDeleted($borrowernumber);
1613 Copy the record from borrowers to deletedborrowers table.
1617 # FIXME: should do it in one SQL statement w/ subquery
1618 # Otherwise, we should return the @data on success
1620 sub MoveMemberToDeleted {
1621 my ($member) = shift or return;
1622 my $dbh = C4::Context->dbh;
1623 my $query = qq|SELECT *
1625 WHERE borrowernumber=?|;
1626 my $sth = $dbh->prepare($query);
1627 $sth->execute($member);
1628 my @data = $sth->fetchrow_array;
1629 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1631 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1632 . ( "?," x ( scalar(@data) - 1 ) )
1634 $sth->execute(@data);
1639 DelMember($borrowernumber);
1641 This function remove directly a borrower whitout writing it on deleteborrower.
1642 + Deletes reserves for the borrower
1647 my $dbh = C4::Context->dbh;
1648 my $borrowernumber = shift;
1649 #warn "in delmember with $borrowernumber";
1650 return unless $borrowernumber; # borrowernumber is mandatory.
1652 my $query = qq|DELETE
1654 WHERE borrowernumber=?|;
1655 my $sth = $dbh->prepare($query);
1656 $sth->execute($borrowernumber);
1660 WHERE borrowernumber = ?
1662 $sth = $dbh->prepare($query);
1663 $sth->execute($borrowernumber);
1664 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1668 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1670 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1672 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1677 sub ExtendMemberSubscriptionTo {
1678 my ( $borrowerid,$date) = @_;
1679 my $dbh = C4::Context->dbh;
1680 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1682 $date=POSIX::strftime("%Y-%m-%d",localtime());
1683 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1685 my $sth = $dbh->do(<<EOF);
1687 SET dateexpiry='$date'
1688 WHERE borrowernumber='$borrowerid'
1690 # add enrolmentfee if needed
1691 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1692 $sth->execute($borrower->{'categorycode'});
1693 my ($enrolmentfee) = $sth->fetchrow;
1694 if ($enrolmentfee && $enrolmentfee > 0) {
1695 # insert fee in patron debts
1696 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1698 return $date if ($sth);
1702 =head2 GetRoadTypes (OUEST-PROVENCE)
1704 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1706 Looks up the different road type . Returns two
1707 elements: a reference-to-array, which lists the id_roadtype
1708 codes, and a reference-to-hash, which maps the road type of the road .
1713 my $dbh = C4::Context->dbh;
1715 SELECT roadtypeid,road_type
1717 ORDER BY road_type|;
1718 my $sth = $dbh->prepare($query);
1723 # insert empty value to create a empty choice in cgi popup
1725 while ( my $data = $sth->fetchrow_hashref ) {
1727 push @id, $data->{'roadtypeid'};
1728 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1731 #test to know if the table contain some records if no the function return nothing
1738 return ( \@id, \%roadtype );
1744 =head2 GetTitles (OUEST-PROVENCE)
1746 ($borrowertitle)= &GetTitles();
1748 Looks up the different title . Returns array with all borrowers title
1753 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1754 unshift( @borrowerTitle, "" );
1755 my $count=@borrowerTitle;
1760 return ( \@borrowerTitle);
1764 =head2 GetPatronImage
1766 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1768 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1772 sub GetPatronImage {
1773 my ($cardnumber) = @_;
1774 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1775 my $dbh = C4::Context->dbh;
1776 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1777 my $sth = $dbh->prepare($query);
1778 $sth->execute($cardnumber);
1779 my $imagedata = $sth->fetchrow_hashref;
1780 warn "Database error!" if $sth->errstr;
1781 return $imagedata, $sth->errstr;
1784 =head2 PutPatronImage
1786 PutPatronImage($cardnumber, $mimetype, $imgfile);
1788 Stores patron binary image data and mimetype in database.
1789 NOTE: This function is good for updating images as well as inserting new images in the database.
1793 sub PutPatronImage {
1794 my ($cardnumber, $mimetype, $imgfile) = @_;
1795 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1796 my $dbh = C4::Context->dbh;
1797 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1798 my $sth = $dbh->prepare($query);
1799 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1800 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1801 return $sth->errstr;
1804 =head2 RmPatronImage
1806 my ($dberror) = RmPatronImage($cardnumber);
1808 Removes the image for the patron with the supplied cardnumber.
1813 my ($cardnumber) = @_;
1814 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1815 my $dbh = C4::Context->dbh;
1816 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1817 my $sth = $dbh->prepare($query);
1818 $sth->execute($cardnumber);
1819 my $dberror = $sth->errstr;
1820 warn "Database error!" if $sth->errstr;
1824 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1826 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1828 Returns the description of roadtype
1829 C<&$roadtype>return description of road type
1830 C<&$roadtypeid>this is the value of roadtype s
1834 sub GetRoadTypeDetails {
1835 my ($roadtypeid) = @_;
1836 my $dbh = C4::Context->dbh;
1840 WHERE roadtypeid=?|;
1841 my $sth = $dbh->prepare($query);
1842 $sth->execute($roadtypeid);
1843 my $roadtype = $sth->fetchrow;
1847 =head2 GetBorrowersWhoHaveNotBorrowedSince
1849 &GetBorrowersWhoHaveNotBorrowedSince($date)
1851 this function get all borrowers who haven't borrowed since the date given on input arg.
1855 sub GetBorrowersWhoHaveNotBorrowedSince {
1856 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1857 my $filterexpiry = shift;
1858 my $filterbranch = shift ||
1859 ((C4::Context->preference('IndependantBranches')
1860 && C4::Context->userenv
1861 && C4::Context->userenv->{flags} % 2 !=1
1862 && C4::Context->userenv->{branch})
1863 ? C4::Context->userenv->{branch}
1865 my $dbh = C4::Context->dbh;
1867 SELECT borrowers.borrowernumber,
1868 max(old_issues.timestamp) as latestissue,
1869 max(issues.timestamp) as currentissue
1871 JOIN categories USING (categorycode)
1872 LEFT JOIN old_issues USING (borrowernumber)
1873 LEFT JOIN issues USING (borrowernumber)
1874 WHERE category_type <> 'S'
1875 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1878 if ($filterbranch && $filterbranch ne ""){
1879 $query.=" AND borrowers.branchcode= ?";
1880 push @query_params,$filterbranch;
1883 $query .= " AND dateexpiry < ? ";
1884 push @query_params,$filterdate;
1886 $query.=" GROUP BY borrowers.borrowernumber";
1888 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1889 AND currentissue IS NULL";
1890 push @query_params,$filterdate;
1892 warn $query if $debug;
1893 my $sth = $dbh->prepare($query);
1894 if (scalar(@query_params)>0){
1895 $sth->execute(@query_params);
1902 while ( my $data = $sth->fetchrow_hashref ) {
1903 push @results, $data;
1908 =head2 GetBorrowersWhoHaveNeverBorrowed
1910 $results = &GetBorrowersWhoHaveNeverBorrowed
1912 this function get all borrowers who have never borrowed.
1914 I<$result> is a ref to an array which all elements are a hasref.
1918 sub GetBorrowersWhoHaveNeverBorrowed {
1919 my $filterbranch = shift ||
1920 ((C4::Context->preference('IndependantBranches')
1921 && C4::Context->userenv
1922 && C4::Context->userenv->{flags} % 2 !=1
1923 && C4::Context->userenv->{branch})
1924 ? C4::Context->userenv->{branch}
1926 my $dbh = C4::Context->dbh;
1928 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1930 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1931 WHERE issues.borrowernumber IS NULL
1934 if ($filterbranch && $filterbranch ne ""){
1935 $query.=" AND borrowers.branchcode= ?";
1936 push @query_params,$filterbranch;
1938 warn $query if $debug;
1940 my $sth = $dbh->prepare($query);
1941 if (scalar(@query_params)>0){
1942 $sth->execute(@query_params);
1949 while ( my $data = $sth->fetchrow_hashref ) {
1950 push @results, $data;
1955 =head2 GetBorrowersWithIssuesHistoryOlderThan
1957 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1959 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1961 I<$result> is a ref to an array which all elements are a hashref.
1962 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1966 sub GetBorrowersWithIssuesHistoryOlderThan {
1967 my $dbh = C4::Context->dbh;
1968 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1969 my $filterbranch = shift ||
1970 ((C4::Context->preference('IndependantBranches')
1971 && C4::Context->userenv
1972 && C4::Context->userenv->{flags} % 2 !=1
1973 && C4::Context->userenv->{branch})
1974 ? C4::Context->userenv->{branch}
1977 SELECT count(borrowernumber) as n,borrowernumber
1979 WHERE returndate < ?
1980 AND borrowernumber IS NOT NULL
1983 push @query_params, $date;
1985 $query.=" AND branchcode = ?";
1986 push @query_params, $filterbranch;
1988 $query.=" GROUP BY borrowernumber ";
1989 warn $query if $debug;
1990 my $sth = $dbh->prepare($query);
1991 $sth->execute(@query_params);
1994 while ( my $data = $sth->fetchrow_hashref ) {
1995 push @results, $data;
2000 =head2 GetBorrowersNamesAndLatestIssue
2002 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2004 this function get borrowers Names and surnames and Issue information.
2006 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2007 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2011 sub GetBorrowersNamesAndLatestIssue {
2012 my $dbh = C4::Context->dbh;
2013 my @borrowernumbers=@_;
2015 SELECT surname,lastname, phone, email,max(timestamp)
2017 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2018 GROUP BY borrowernumber
2020 my $sth = $dbh->prepare($query);
2022 my $results = $sth->fetchall_arrayref({});
2030 my $success = DebarMember( $borrowernumber );
2032 marks a Member as debarred, and therefore unable to checkout any more
2036 true on success, false on failure
2043 my $borrowernumber = shift;
2045 return unless defined $borrowernumber;
2046 return unless $borrowernumber =~ /^\d+$/;
2048 return ModMember( borrowernumber => $borrowernumber,
2057 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2059 Adds a message to the messages table for the given borrower.
2070 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2072 my $dbh = C4::Context->dbh;
2074 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2078 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2079 my $sth = $dbh->prepare($query);
2080 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2089 GetMessages( $borrowernumber, $type );
2091 $type is message type, B for borrower, or L for Librarian.
2092 Empty type returns all messages of any type.
2094 Returns all messages for the given borrowernumber
2101 my ( $borrowernumber, $type, $branchcode ) = @_;
2107 my $dbh = C4::Context->dbh;
2110 branches.branchname,
2112 DATE_FORMAT( message_date, '%m/%d/%Y' ) AS message_date_formatted,
2113 messages.branchcode LIKE '$branchcode' AS can_delete
2114 FROM messages, branches
2115 WHERE borrowernumber = ?
2116 AND message_type LIKE ?
2117 AND messages.branchcode = branches.branchcode
2118 ORDER BY message_date DESC";
2119 my $sth = $dbh->prepare($query);
2120 $sth->execute( $borrowernumber, $type ) ;
2123 while ( my $data = $sth->fetchrow_hashref ) {
2124 push @results, $data;
2134 GetMessagesCount( $borrowernumber, $type );
2136 $type is message type, B for borrower, or L for Librarian.
2137 Empty type returns all messages of any type.
2139 Returns the number of messages for the given borrowernumber
2145 sub GetMessagesCount {
2146 my ( $borrowernumber, $type, $branchcode ) = @_;
2152 my $dbh = C4::Context->dbh;
2154 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2155 my $sth = $dbh->prepare($query);
2156 $sth->execute( $borrowernumber, $type ) ;
2159 my $data = $sth->fetchrow_hashref;
2160 my $count = $data->{'MsgCount'};
2167 =head2 DeleteMessage
2171 DeleteMessage( $message_id );
2178 my ( $message_id ) = @_;
2180 my $dbh = C4::Context->dbh;
2182 my $query = "DELETE FROM messages WHERE message_id = ?";
2183 my $sth = $dbh->prepare($query);
2184 $sth->execute( $message_id );
2188 END { } # module clean-up code here (global destructor)