X-Git-Url: http://koha-dev.rot13.org:8081/gitweb/?a=blobdiff_plain;f=C4%2FMembers.pm;h=13244e08bf2f8189b76e5b69fdf132c5f72f9e14;hb=ef5d4f3c62957100dae0948a44bd27a2159892b4;hp=dcc168b9c40aebb15fb5e2b64c246188a3266186;hpb=6be9d2b27dd47c859eb6ab0cfd873b2059206986;p=koha_fer diff --git a/C4/Members.pm b/C4/Members.pm index dcc168b9c4..13244e08bf 100644 --- a/C4/Members.pm +++ b/C4/Members.pm @@ -2,6 +2,7 @@ package C4::Members; # Copyright 2000-2003 Katipo Communications # Copyright 2010 BibLibre +# Parts Copyright 2010 Catalyst IT # # This file is part of Koha. # @@ -22,98 +23,110 @@ package C4::Members; use strict; #use warnings; FIXME - Bug 2505 use C4::Context; -use C4::Dates qw(format_date_in_iso); -use Digest::MD5 qw(md5_base64); -use Date::Calc qw/Today Add_Delta_YM/; +use C4::Dates qw(format_date_in_iso format_date); +use String::Random qw( random_string ); +use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/; use C4::Log; # logaction use C4::Overdues; use C4::Reserves; use C4::Accounts; use C4::Biblio; +use C4::Letters; use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable); use C4::Members::Attributes qw(SearchIdMatchingAttribute); +use C4::NewsChannels; #get slip news +use DateTime; +use DateTime::Format::DateParse; +use Koha::DateUtils; +use Koha::Borrower::Debarments qw(IsDebarred); +use Text::Unaccent qw( unac_string ); +use Koha::AuthUtils qw(hash_password); +use Koha::Database; our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug); BEGIN { - $VERSION = 3.02; - $debug = $ENV{DEBUG} || 0; - require Exporter; - @ISA = qw(Exporter); - #Get data - push @EXPORT, qw( - &Search - &SearchMember - &GetMemberDetails + $VERSION = 3.07.00.049; + $debug = $ENV{DEBUG} || 0; + require Exporter; + @ISA = qw(Exporter); + #Get data + push @EXPORT, qw( + &Search + &GetMemberDetails &GetMemberRelatives - &GetMember + &GetMember + + &GetGuarantees - &GetGuarantees + &GetMemberIssuesAndFines + &GetPendingIssues + &GetAllIssues - &GetMemberIssuesAndFines - &GetPendingIssues - &GetAllIssues + &getzipnamecity + &getidcity - &get_institutions - &getzipnamecity - &getidcity + &GetFirstValidEmailAddress + &GetNoticeEmailAddress - &GetFirstValidEmailAddress + &GetAge + &GetCities + &GetSortDetails + &GetTitles - &GetAge - &GetCities - &GetRoadTypes - &GetRoadTypeDetails - &GetSortDetails - &GetTitles + &GetPatronImage + &PutPatronImage + &RmPatronImage - &GetPatronImage - &PutPatronImage - &RmPatronImage + &GetHideLostItemsPreference - &GetHideLostItemsPreference + &IsMemberBlocked + &GetMemberAccountRecords + &GetBorNotifyAcctRecord - &IsMemberBlocked - &GetMemberAccountRecords - &GetBorNotifyAcctRecord + &GetborCatFromCatType + &GetBorrowercategory + GetBorrowerCategorycode + &GetBorrowercategoryList - &GetborCatFromCatType - &GetBorrowercategory - &GetBorrowercategoryList + &GetBorrowersToExpunge + &GetBorrowersWhoHaveNeverBorrowed + &GetBorrowersWithIssuesHistoryOlderThan - &GetBorrowersWhoHaveNotBorrowedSince - &GetBorrowersWhoHaveNeverBorrowed - &GetBorrowersWithIssuesHistoryOlderThan + &GetExpiryDate - &GetExpiryDate + &AddMessage + &DeleteMessage + &GetMessages + &GetMessagesCount - &AddMessage - &DeleteMessage - &GetMessages - &GetMessagesCount - ); + &IssueSlip + GetBorrowersWithEmail + + HasOverdues + ); - #Modify data - push @EXPORT, qw( - &ModMember - &changepassword + #Modify data + push @EXPORT, qw( + &ModMember + &changepassword &ModPrivacy - ); - - #Delete data - push @EXPORT, qw( - &DelMember - ); - - #Insert data - push @EXPORT, qw( - &AddMember - &add_member_orgs - &MoveMemberToDeleted - &ExtendMemberSubscriptionTo - ); - - #Check data + ); + + #Delete data + push @EXPORT, qw( + &DelMember + ); + + #Insert data + push @EXPORT, qw( + &AddMember + &AddMember_Opac + &MoveMemberToDeleted + &ExtendMemberSubscriptionTo + ); + + #Check data push @EXPORT, qw( &checkuniquemember &checkuserpassword @@ -140,178 +153,137 @@ This module contains routines for adding, modifying and deleting members/patrons =head1 FUNCTIONS -=head2 SearchMember - - ($count, $borrowers) = &SearchMember($searchstring, $type, - $category_type, $filter, $showallbranches); +=head2 Search -Looks up patrons (borrowers) by name. + $borrowers_result_array_ref = &Search($filter,$orderby, $limit, + $columns_out, $search_on_fields,$searchtype); -BUGFIX 499: C<$type> is now used to determine type of search. -if $type is "simple", search is performed on the first letter of the -surname only. +Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers'). -$category_type is used to get a specified type of user. -(mainly adults when creating a child.) +For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype> +refer to C4::SQLHelper:SearchInTable(). -C<$searchstring> is a space-separated list of search terms. Each term -must match the beginning a borrower's surname, first name, or other -name. +Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw +and cardnumber unless C<&search_on_fields> is defined -C<$filter> is assumed to be a list of elements to filter results on +Examples: -C<$showallbranches> is used in IndependantBranches Context to display all branches results. + $borrowers = Search('abcd', 'cardnumber'); -C<&SearchMember> returns a two-element list. C<$borrowers> is a -reference-to-array; each element is a reference-to-hash, whose keys -are the fields of the C table in the Koha database. -C<$count> is the number of elements in C<$borrowers>. + $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname'); =cut -#' -#used by member enquiries from the intranet -sub SearchMember { - my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_; - my $dbh = C4::Context->dbh; - my $query = ""; - my $count; - my @data; - my @bind = (); - +sub _express_member_find { + my ($filter) = @_; + # this is used by circulation everytime a new borrowers cardnumber is scanned # so we can check an exact match first, if that works return, otherwise do the rest - $query = "SELECT * FROM borrowers - LEFT JOIN categories ON borrowers.categorycode=categories.categorycode - "; - my $sth = $dbh->prepare("$query WHERE cardnumber = ?"); - $sth->execute($searchstring); - my $data = $sth->fetchall_arrayref({}); - if (@$data){ - return ( scalar(@$data), $data ); - } - - if ( $type eq "simple" ) # simple search for one letter only - { - $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : ""); - $query .= " WHERE (surname LIKE ? OR cardnumber like ?) "; - if (C4::Context->preference("IndependantBranches") && !$showallbranches){ - if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){ - $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure"); - } - } - $query.=" ORDER BY $orderby"; - @bind = ("$searchstring%","$searchstring"); + my $dbh = C4::Context->dbh; + my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?"; + if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) { + return( {"borrowernumber"=>$borrowernumber} ); } - else # advanced search looking in surname, firstname and othernames - { - @data = split( ' ', $searchstring ); - $count = @data; - $query .= " WHERE "; - if (C4::Context->preference("IndependantBranches") && !$showallbranches){ - if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){ - $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure"); - } - } - $query.="((surname LIKE ? OR (surname LIKE ? AND surname REGEXP ?) - OR firstname LIKE ? OR (firstname LIKE ? AND firstname REGEXP ?) - OR othernames LIKE ? OR (othernames LIKE ? AND othernames REGEXP ?)) - " . - ($category_type?" AND category_type = ".$dbh->quote($category_type):""); - my $regex = '[[:punct:][:space:]]'.$data[0]; - @bind = ( - "$data[0]%", "%$data[0]%", $regex, - "$data[0]%", "%$data[0]%", $regex, - "$data[0]%", "%$data[0]%", $regex - ); - for ( my $i = 1 ; $i < $count ; $i++ ) { - $query = $query . " AND (" . " surname LIKE ? OR (surname LIKE ? AND surname REGEXP ?) - OR firstname LIKE ? OR (firstname LIKE ? AND firstname REGEXP ?) - OR othernames LIKE ? OR (othernames LIKE ? AND othernames REGEXP ?))"; - $regex = '[[:punct:][:space:]]'.$data[$i]; - push( @bind, - "$data[$i]%", "%$data[$i]%", $regex, - "$data[$i]%", "%$data[$i]%", $regex, - "$data[$i]%", "%$data[$i]%", $regex - ); - - - # FIXME - .= <prepare($query); - - $debug and print STDERR "Q $orderby : $query\n"; - $sth->execute(@bind); - my @results; - $data = $sth->fetchall_arrayref({}); - - return ( scalar(@$data), $data ); + return (undef, $search_on_fields, $searchtype); } -=head2 Search - - $borrowers_result_array_ref = &Search($filter,$orderby, $limit, - $columns_out, $search_on_fields,$searchtype); - -Looks up patrons (borrowers) on filter. - -BUGFIX 499: C<$type> is now used to determine type of search. -if $type is "simple", search is performed on the first letter of the -surname only. - -$category_type is used to get a specified type of user. -(mainly adults when creating a child.) - -C<$filter> can be - - a space-separated list of search terms. Implicit AND is done on them - - a hash ref containing fieldnames associated with queried value - - an array ref combining the two previous elements Implicit OR is done between each array element - - -C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending - -C<$limit> is there to allow limiting number of results returned - -C<&columns_out> is an array ref to the fieldnames you want to see in the result list - -C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search - -C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed - -=cut - sub Search { my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_; - my @filters; - my %filtersmatching_record; - my @finalfilter; - if ( ref($filter) eq "ARRAY" ) { - push @filters, @$filter; - } else { - push @filters, $filter; + + my $search_string; + my $found_borrower; + + if ( my $fr = ref $filter ) { + if ( $fr eq "HASH" ) { + if ( my $search_string = $filter->{''} ) { + my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string); + if ($member_filter) { + $filter = $member_filter; + $found_borrower = 1; + } else { + $search_on_fields ||= $member_search_on_fields; + $searchtype ||= $member_searchtype; + } + } + } + else { + $search_string = $filter; + } + } + else { + $search_string = $filter; + my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string); + if ($member_filter) { + $filter = $member_filter; + $found_borrower = 1; + } else { + $search_on_fields ||= $member_search_on_fields; + $searchtype ||= $member_searchtype; + } } - if ( C4::Context->preference('ExtendedPatronAttributes') ) { - my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter); + + if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) { + my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string); if(scalar(@$matching_records)>0) { - foreach my $matching_record (@$matching_records) { - $filtersmatching_record{$$matching_record[0]}=1; - } - foreach my $k (keys(%filtersmatching_record)) { - push @filters, {"borrowernumber"=>$k}; - } - } + if ( my $fr = ref $filter ) { + if ( $fr eq "HASH" ) { + my %f = %$filter; + $filter = [ $filter ]; + delete $f{''}; + push @$filter, { %f, "borrowernumber"=>$$matching_records }; + } + else { + push @$filter, {"borrowernumber"=>$matching_records}; + } + } + else { + $filter = [ $filter ]; + push @$filter, {"borrowernumber"=>$matching_records}; + } + } + } + + # $showallbranches was not used at the time SearchMember() was mainstreamed into Search(). + # Mentioning for the reference + + if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){ + if ( my $userenv = C4::Context->userenv ) { + my $branch = $userenv->{'branch'}; + if ( !C4::Context->IsSuperLibrarian() && $branch ){ + if (my $fr = ref $filter) { + if ( $fr eq "HASH" ) { + $filter->{branchcode} = $branch; + } + else { + foreach (@$filter) { + $_ = { '' => $_ } unless ref $_; + $_->{branchcode} = $branch; + } + } + } + else { + $filter = { '' => $filter, branchcode => $branch }; + } + } + } + } + + if ($found_borrower) { + $searchtype = "exact"; } $searchtype ||= "start_with"; - push @finalfilter, \@filters; - my $data = SearchInTable( "borrowers", \@finalfilter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ); - return ($data); + + return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ); } =head2 GetMemberDetails @@ -352,17 +324,38 @@ sub GetMemberDetails { my $query; my $sth; if ($borrowernumber) { - $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"); + $sth = $dbh->prepare(" + SELECT borrowers.*, + category_type, + categories.description, + categories.BlockExpiredPatronOpacActions, + reservefee, + enrolmentperiod + FROM borrowers + LEFT JOIN categories ON borrowers.categorycode=categories.categorycode + WHERE borrowernumber = ? + "); $sth->execute($borrowernumber); } elsif ($cardnumber) { - $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?"); + $sth = $dbh->prepare(" + SELECT borrowers.*, + category_type, + categories.description, + categories.BlockExpiredPatronOpacActions, + reservefee, + enrolmentperiod + FROM borrowers + LEFT JOIN categories ON borrowers.categorycode = categories.categorycode + WHERE cardnumber = ? + "); $sth->execute($cardnumber); } else { - return undef; + return; } my $borrower = $sth->fetchrow_hashref; + return unless $borrower; my ($amount) = GetMemberAccountRecords( $borrowernumber); $borrower->{'amountoutstanding'} = $amount; # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount @@ -379,13 +372,28 @@ sub GetMemberDetails { $borrower->{'flags'} = $flags; $borrower->{'authflags'} = $accessflagshash; - # find out how long the membership lasts - $sth = - $dbh->prepare( - "select enrolmentperiod from categories where categorycode = ?"); - $sth->execute( $borrower->{'categorycode'} ); - my $enrolment = $sth->fetchrow; - $borrower->{'enrolmentperiod'} = $enrolment; + # For the purposes of making templates easier, we'll define a + # 'showname' which is the alternate form the user's first name if + # 'other name' is defined. + if ($borrower->{category_type} eq 'I') { + $borrower->{'showname'} = $borrower->{'othernames'}; + $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'}; + } else { + $borrower->{'showname'} = $borrower->{'firstname'}; + } + + # Handle setting the true behavior for BlockExpiredPatronOpacActions + $borrower->{'BlockExpiredPatronOpacActions'} = + C4::Context->preference('BlockExpiredPatronOpacActions') + if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 ); + + $borrower->{'is_expired'} = 0; + $borrower->{'is_expired'} = 1 if + defined($borrower->{dateexpiry}) && + $borrower->{'dateexpiry'} ne '0000-00-00' && + Date_to_Days( Today() ) > + Date_to_Days( split /-/, $borrower->{'dateexpiry'} ); + return ($borrower); #, $flags, $accessflagshash); } @@ -456,21 +464,21 @@ sub patronflags { my %flags; my ( $patroninformation) = @_; my $dbh=C4::Context->dbh; - my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'}); - if ( $amount > 0 ) { + my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'}); + if ( $owing > 0 ) { my %flaginfo; my $noissuescharge = C4::Context->preference("noissuescharge") || 5; - $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount; - $flaginfo{'amount'} = sprintf "%.02f", $amount; - if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) { + $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing; + $flaginfo{'amount'} = sprintf "%.02f", $owing; + if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) { $flaginfo{'noissues'} = 1; } $flags{'CHARGES'} = \%flaginfo; } - elsif ( $amount < 0 ) { + elsif ( $balance < 0 ) { my %flaginfo; - $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount; - $flaginfo{'amount'} = sprintf "%.02f", $amount; + $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance; + $flaginfo{'amount'} = sprintf "%.02f", $balance; $flags{'CREDITS'} = \%flaginfo; } if ( $patroninformation->{'gonenoaddress'} @@ -487,13 +495,15 @@ sub patronflags { $flaginfo{'noissues'} = 1; $flags{'LOST'} = \%flaginfo; } - if ( $patroninformation->{'debarred'} - && $patroninformation->{'debarred'} == 1 ) - { - my %flaginfo; - $flaginfo{'message'} = 'Borrower is Debarred.'; - $flaginfo{'noissues'} = 1; - $flags{'DBARRED'} = \%flaginfo; + if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) { + if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) { + my %flaginfo; + $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'}; + $flaginfo{'message'} = $patroninformation->{'debarredcomment'}; + $flaginfo{'noissues'} = 1; + $flaginfo{'dateend'} = $patroninformation->{'debarred'}; + $flags{'DBARRED'} = \%flaginfo; + } } if ( $patroninformation->{'borrowernotes'} && $patroninformation->{'borrowernotes'} ) @@ -502,7 +512,7 @@ sub patronflags { $flaginfo{'message'} = $patroninformation->{'borrowernotes'}; $flags{'NOTES'} = \%flaginfo; } - my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'}); + my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'}); if ( $odues && $odues > 0 ) { my %flaginfo; $flaginfo{'message'} = "Yes"; @@ -607,7 +617,7 @@ sub GetMemberRelatives { $sth->execute($borrowernumber); my $data = $sth->fetchrow_arrayref(); push @glist, $data->[0] if $data->[0]; - my $guarantor = $data->[0] if $data->[0]; + my $guarantor = $data->[0] ? $data->[0] : undef; # Getting guarantees $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?"; @@ -659,50 +669,23 @@ sub IsMemberBlocked { my $borrowernumber = shift; my $dbh = C4::Context->dbh; - # does patron have current fine days? - my $strsth=qq{ - SELECT - ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate, - DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount - FROM old_issues - }; - if(C4::Context->preference("item-level_itypes")){ - $strsth.= - qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber) - LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)} - }else{ - $strsth .= - qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber) - LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) - LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) }; - } - $strsth.= - qq{ WHERE finedays IS NOT NULL - AND date_due < returndate - AND borrowernumber = ? - ORDER BY blockingdate DESC, blockedcount DESC - LIMIT 1}; - my $sth=$dbh->prepare($strsth); - $sth->execute($borrowernumber); - my $row = $sth->fetchrow_hashref; - my $blockeddate = $row->{'blockeddate'}; - my $blockedcount = $row->{'blockedcount'}; + my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber); - return (1, $blockedcount) if $blockedcount > 0; + return ( 1, $blockeddate ) if $blockeddate; # if he have late issues - $sth = $dbh->prepare( + my $sth = $dbh->prepare( "SELECT COUNT(*) as latedocs FROM issues WHERE borrowernumber = ? - AND date_due < curdate()" + AND date_due < now()" ); $sth->execute($borrowernumber); my $latedocs = $sth->fetchrow_hashref->{'latedocs'}; - return (-1, $latedocs) if $latedocs > 0; + return ( -1, $latedocs ) if $latedocs > 0; - return (0, 0); + return ( 0, 0 ); } =head2 GetMemberIssuesAndFines @@ -733,7 +716,7 @@ sub GetMemberIssuesAndFines { $sth = $dbh->prepare( "SELECT COUNT(*) FROM issues WHERE borrowernumber = ? - AND date_due < curdate()" + AND date_due < now()" ); $sth->execute($borrowernumber); my $overdue_count = $sth->fetchrow_arrayref->[0]; @@ -745,10 +728,42 @@ sub GetMemberIssuesAndFines { return ($overdue_count, $issue_count, $total_fines); } -sub columns(;$) { - return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")}; + +=head2 columns + + my @columns = C4::Member::columns(); + +Returns an array of borrowers' table columns on success, +and an empty array on failure. + +=cut + +sub columns { + + # Pure ANSI SQL goodness. + my $sql = 'SELECT * FROM borrowers WHERE 1=0;'; + + # Get the database handle. + my $dbh = C4::Context->dbh; + + # Run the SQL statement to load STH's readonly properties. + my $sth = $dbh->prepare($sql); + my $rv = $sth->execute(); + + # This only fails if the table doesn't exist. + # This will always be called AFTER an install or upgrade, + # so borrowers will exist! + my @data; + if ($sth->{NUM_OF_FIELDS}>0) { + @data = @{$sth->{NAME}}; + } + else { + @data = (); + } + return @data; } + =head2 ModMember my $success = ModMember(borrowernumber => $borrowernumber, @@ -768,10 +783,11 @@ sub ModMember { if ($data{password} eq '****' or $data{password} eq '') { delete $data{password}; } else { - $data{password} = md5_base64($data{password}); + $data{password} = hash_password($data{password}); } } - my $execute_success=UpdateInTable("borrowers",\%data); + my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} ); + my $execute_success=UpdateInTable("borrowers",\%data); if ($execute_success) { # only proceed if the update was a success # ok if its an adult (type) it may have borrowers that depend on it as a guarantor # so when we update information for an adult we should check for guarantees and update the relevant part @@ -781,12 +797,17 @@ sub ModMember { # is adult check guarantees; UpdateGuarantees(%data); } + + # If the patron changes to a category with enrollment fee, we add a fee + if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) { + AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} ); + } + logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog"); } return $execute_success; } - =head2 AddMember $borrowernumber = &AddMember(%borrower); @@ -802,41 +823,64 @@ Returns as undef upon any db error without further processing sub AddMember { my (%data) = @_; my $dbh = C4::Context->dbh; - # generate a proper login if none provided - $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq ''; - # create a disabled account if no password provided - $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!'; - $data{'borrowernumber'}=InsertInTable("borrowers",\%data); - # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best. - logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog"); - - # check for enrollment fee & add it if needed - my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?"); - $sth->execute($data{'categorycode'}); - my ($enrolmentfee) = $sth->fetchrow; - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); - return; + + # generate a proper login if none provided + $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq ''; + + # add expiration date if it isn't already there + unless ( $data{'dateexpiry'} ) { + $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") ); } - if ($enrolmentfee && $enrolmentfee > 0) { - # insert fee in patron debts - manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee); + + # add enrollment date if it isn't already there + unless ( $data{'dateenrolled'} ) { + $data{'dateenrolled'} = C4::Dates->new()->output("iso"); } + my $patron_category = + Koha::Database->new()->schema()->resultset('Category') + ->find( $data{'categorycode'} ); + $data{'privacy'} = + $patron_category->default_privacy() eq 'default' ? 1 + : $patron_category->default_privacy() eq 'never' ? 2 + : $patron_category->default_privacy() eq 'forever' ? 0 + : undef; + + # create a disabled account if no password provided + $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!'; + $data{'borrowernumber'}=InsertInTable("borrowers",\%data); + + # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best. + logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog"); + + AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} ); + return $data{'borrowernumber'}; } +=head2 Check_Userid + + my $uniqueness = Check_Userid($userid,$borrowernumber); + + $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != ''). + + If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided. + + return : + 0 for not unique (i.e. this $userid already exists) + 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists) + +=cut sub Check_Userid { my ($uid,$member) = @_; my $dbh = C4::Context->dbh; - # Make sure the userid chosen is unique and not theirs if non-empty. If it is not, - # Then we need to tell the user and have them create a new one. my $sth = $dbh->prepare( "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?"); $sth->execute( $uid, $member ); - if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) { + if ( (( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref )) or + (( $uid ne '' ) && ( $uid eq C4::Context->config('user') )) ) { return 0; } else { @@ -844,14 +888,29 @@ sub Check_Userid { } } +=head2 Generate_Userid + + my $newuid = Generate_Userid($borrowernumber, $firstname, $surname); + + Generate a userid using the $surname and the $firstname (if there is a value in $firstname). + + $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub. + + return : + new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database). + +=cut + sub Generate_Userid { my ($borrowernumber, $firstname, $surname) = @_; my $newuid; my $offset = 0; + #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique) do { $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g; $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g; $newuid = lc(($firstname)? "$firstname.$surname" : $surname); + $newuid = unac_string('utf-8',$newuid); $newuid .= $offset unless $offset == 0; $offset++; @@ -899,7 +958,7 @@ mode, to avoid database corruption. use vars qw( @weightings ); my @weightings = ( 8, 4, 6, 3, 5, 2, 1 ); -sub fixup_cardnumber ($) { +sub fixup_cardnumber { my ($cardnumber) = @_; my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0; @@ -949,11 +1008,8 @@ sub fixup_cardnumber ($) { return "V$cardnumber$rem"; } else { - # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably - # better. I'll leave the original in in case it needs to be changed for you - # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers"); my $sth = $dbh->prepare( - "select max(cast(cardnumber as signed)) from borrowers" + 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"' ); $sth->execute; my ($result) = $sth->fetchrow; @@ -1041,7 +1097,7 @@ sub GetPendingIssues { # Borrowers part of the query my $bquery = ''; for (my $i = 0; $i < @borrowernumbers; $i++) { - $bquery .= ' borrowernumber = ?'; + $bquery .= ' issues.borrowernumber = ?'; if ($i < $#borrowernumbers ) { $bquery .= ' OR'; } @@ -1050,7 +1106,6 @@ sub GetPendingIssues { # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ? # FIXME: circ/ciculation.pl tries to sort by timestamp! - # FIXME: C4::Print::printslip tries to sort by timestamp! # FIXME: namespace collision: other collisions possible. # FIXME: most of this data isn't really being used by callers. my $query = @@ -1068,6 +1123,9 @@ sub GetPendingIssues { biblioitems.volumedesc, biblioitems.lccn, biblioitems.url, + borrowers.firstname, + borrowers.surname, + borrowers.cardnumber, issues.timestamp AS timestamp, issues.renewals AS renewals, issues.borrowernumber AS borrowernumber, @@ -1076,6 +1134,7 @@ sub GetPendingIssues { LEFT JOIN items ON items.itemnumber = issues.itemnumber LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber + LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber WHERE $bquery ORDER BY issues.issuedate" @@ -1084,9 +1143,15 @@ sub GetPendingIssues { my $sth = C4::Context->dbh->prepare($query); $sth->execute(@borrowernumbers); my $data = $sth->fetchall_arrayref({}); - my $today = C4::Dates->new->output('iso'); + my $tz = C4::Context->tz(); + my $today = DateTime->now( time_zone => $tz); foreach (@{$data}) { - if ($_->{date_due} and $_->{date_due} lt $today) { + if ($_->{issuedate}) { + $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql'); + } + $_->{date_due} or next; + $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name()); + if ( DateTime->compare($_->{date_due}, $today) == -1 ) { $_->{overdue} = 1; } } @@ -1116,10 +1181,9 @@ C tables of the Koha database. sub GetAllIssues { my ( $borrowernumber, $order, $limit ) = @_; - #FIXME: sanity-check order and limit - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = - "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp +'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp FROM issues LEFT JOIN items on items.itemnumber=issues.itemnumber LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber @@ -1132,20 +1196,14 @@ sub GetAllIssues { LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL - order by $order"; - if ( $limit != 0 ) { + order by ' . $order; + if ($limit) { $query .= " limit $limit"; } my $sth = $dbh->prepare($query); - $sth->execute($borrowernumber, $borrowernumber); - my @result; - my $i = 0; - while ( my $data = $sth->fetchrow_hashref ) { - push @result, $data; - } - - return \@result; + $sth->execute( $borrowernumber, $borrowernumber ); + return $sth->fetchall_arrayref( {} ); } @@ -1163,9 +1221,8 @@ total amount outstanding for all of the account lines. =cut -#' sub GetMemberAccountRecords { - my ($borrowernumber,$date) = @_; + my ($borrowernumber) = @_; my $dbh = C4::Context->dbh; my @acctlines; my $numlines = 0; @@ -1173,14 +1230,10 @@ sub GetMemberAccountRecords { SELECT * FROM accountlines WHERE borrowernumber=?); - my @bind = ($borrowernumber); - if ($date && $date ne ''){ - $strsth.=" AND date < ? "; - push(@bind,$date); - } $strsth.=" ORDER BY date desc,timestamp DESC"; my $sth= $dbh->prepare( $strsth ); - $sth->execute( @bind ); + $sth->execute( $borrowernumber ); + my $total = 0; while ( my $data = $sth->fetchrow_hashref ) { if ( $data->{itemnumber} ) { @@ -1196,14 +1249,48 @@ sub GetMemberAccountRecords { return ( $total, \@acctlines,$numlines); } +=head2 GetMemberAccountBalance + + ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber); + +Calculates amount immediately owing by the patron - non-issue charges. +Based on GetMemberAccountRecords. +Charges exempt from non-issue are: +* Res (reserves) +* Rent (rental) if RentalsInNoissuesCharge syspref is set to false +* Manual invoices if ManInvInNoissuesCharge syspref is set to false + +=cut + +sub GetMemberAccountBalance { + my ($borrowernumber) = @_; + + my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous... + + my @not_fines = ('Res'); + push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge'); + unless ( C4::Context->preference('ManInvInNoissuesCharge') ) { + my $dbh = C4::Context->dbh; + my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'}); + push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types; + } + my %not_fine = map {$_ => 1} @not_fines; + + my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber); + my $other_charges = 0; + foreach (@$acctlines) { + $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) }; + } + + return ( $total, $total - $other_charges, $other_charges); +} + =head2 GetBorNotifyAcctRecord - ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid); + ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid); Looks up accounting data for the patron with the given borrowernumber per file number. -(FIXME - I'm not at all sure what this is about.) - C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a reference-to-array, where each element is a reference-to-hash; the keys are the fields of the C table in the Koha database. @@ -1225,11 +1312,15 @@ sub GetBorNotifyAcctRecord { AND amountoutstanding != '0' ORDER BY notify_id,accounttype "); -# 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') $sth->execute( $borrowernumber, $notifyid ); my $total = 0; while ( my $data = $sth->fetchrow_hashref ) { + if ( $data->{itemnumber} ) { + my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} ); + $data->{biblionumber} = $biblio->{biblionumber}; + $data->{title} = $biblio->{title}; + } $acctlines[$numlines] = $data; $numlines++; $total += int(100 * $data->{'amountoutstanding'}); @@ -1278,26 +1369,60 @@ sub checkuniquemember { } sub checkcardnumber { - my ($cardnumber,$borrowernumber) = @_; + my ( $cardnumber, $borrowernumber ) = @_; + # If cardnumber is null, we assume they're allowed. - return 0 if !defined($cardnumber); + return 0 unless defined $cardnumber; + my $dbh = C4::Context->dbh; my $query = "SELECT * FROM borrowers WHERE cardnumber=?"; $query .= " AND borrowernumber <> ?" if ($borrowernumber); - my $sth = $dbh->prepare($query); - if ($borrowernumber) { - $sth->execute($cardnumber,$borrowernumber); - } else { - $sth->execute($cardnumber); - } - if (my $data= $sth->fetchrow_hashref()){ - return 1; - } - else { - return 0; - } -} + my $sth = $dbh->prepare($query); + $sth->execute( + $cardnumber, + ( $borrowernumber ? $borrowernumber : () ) + ); + + return 1 if $sth->fetchrow_hashref; + + my ( $min_length, $max_length ) = get_cardnumber_length(); + return 2 + if length $cardnumber > $max_length + or length $cardnumber < $min_length; + + return 0; +} + +=head2 get_cardnumber_length + + my ($min, $max) = C4::Members::get_cardnumber_length() +Returns the minimum and maximum length for patron cardnumbers as +determined by the CardnumberLength system preference, the +BorrowerMandatoryField system preference, and the width of the +database column. + +=cut + +sub get_cardnumber_length { + my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16) + $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/; + if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) { + # Is integer and length match + if ( $cardnumber_length =~ m|^\d+$| ) { + $min = $max = $cardnumber_length + if $cardnumber_length >= $min + and $cardnumber_length <= $max; + } + # Else assuming it is a range + elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) { + $min = $1 if $1 and $min < $1; + $max = $2 if $2 and $max > $2; + } + + } + return ( $min, $max ); +} =head2 getzipnamecity (OUEST-PROVENCE) @@ -1361,6 +1486,35 @@ sub GetFirstValidEmailAddress { } } +=head2 GetNoticeEmailAddress + + $email = GetNoticeEmailAddress($borrowernumber); + +Return the email address of borrower used for notices, given the borrowernumber. +Returns the empty string if no email address. + +=cut + +sub GetNoticeEmailAddress { + my $borrowernumber = shift; + + my $which_address = C4::Context->preference("AutoEmailPrimaryAddress"); + # if syspref is set to 'first valid' (value == OFF), look up email address + if ( $which_address eq 'OFF' ) { + return GetFirstValidEmailAddress($borrowernumber); + } + # specified email address field + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( qq{ + SELECT $which_address AS primaryemail + FROM borrowers + WHERE borrowernumber=? + } ); + $sth->execute($borrowernumber); + my $data = $sth->fetchrow_hashref; + return $data->{'primaryemail'} || ''; +} + =head2 GetExpiryDate $expirydate = GetExpiryDate($categorycode, $dateenrolled); @@ -1388,28 +1542,6 @@ sub GetExpiryDate { } } -=head2 checkuserpassword (OUEST-PROVENCE) - -check for the password and login are not used -return the number of record -0=> NOT USED 1=> USED - -=cut - -sub checkuserpassword { - my ( $borrowernumber, $userid, $password ) = @_; - $password = md5_base64($password); - my $dbh = C4::Context->dbh; - my $sth = - $dbh->prepare( -"Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? " - ); - $sth->execute( $borrowernumber, $userid, $password ); - my $number_rows = $sth->fetchrow; - return $number_rows; - -} - =head2 GetborCatFromCatType ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType(); @@ -1423,20 +1555,35 @@ to category descriptions. #' sub GetborCatFromCatType { - my ( $category_type, $action ) = @_; - # FIXME - This API seems both limited and dangerous. + my ( $category_type, $action, $no_branch_limit ) = @_; + + my $branch_limit = $no_branch_limit + ? 0 + : C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; + + # FIXME - This API seems both limited and dangerous. my $dbh = C4::Context->dbh; - my $request = qq| SELECT categorycode,description - FROM categories - $action - ORDER BY categorycode|; - my $sth = $dbh->prepare($request); - if ($action) { - $sth->execute($category_type); - } - else { - $sth->execute(); + + my $request = qq{ + SELECT categories.categorycode, categories.description + FROM categories + }; + $request .= qq{ + LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode + } if $branch_limit; + if($action) { + $request .= " $action "; + $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit; + } else { + $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit; } + $request .= " ORDER BY categorycode"; + + my $sth = $dbh->prepare($request); + $sth->execute( + $action ? $category_type : (), + $branch_limit ? $branch_limit : () + ); my %labels; my @codes; @@ -1445,6 +1592,7 @@ sub GetborCatFromCatType { push @codes, $data->{'categorycode'}; $labels{ $data->{'categorycode'} } = $data->{'description'}; } + $sth->finish; return ( \@codes, \%labels ); } @@ -1455,10 +1603,6 @@ sub GetborCatFromCatType { Given the borrower's category code, the function returns the corresponding data hashref for a comprehensive information display. - $arrayref_hashref = &GetBorrowercategory; - -If no category code provided, the function returns all the categories. - =cut sub GetBorrowercategory { @@ -1479,6 +1623,26 @@ sub GetBorrowercategory { return; } # sub getborrowercategory + +=head2 GetBorrowerCategorycode + + $categorycode = &GetBorrowerCategoryCode( $borrowernumber ); + +Given the borrowernumber, the function returns the corresponding categorycode +=cut + +sub GetBorrowerCategorycode { + my ( $borrowernumber ) = @_; + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( qq{ + SELECT categorycode + FROM borrowers + WHERE borrowernumber = ? + } ); + $sth->execute( $borrowernumber ); + return $sth->fetchrow; +} + =head2 GetBorrowercategoryList $arrayref_hashref = &GetBorrowercategoryList; @@ -1487,16 +1651,21 @@ If no category code provided, the function returns all the categories. =cut sub GetBorrowercategoryList { + my $no_branch_limit = @_ ? shift : 0; + my $branch_limit = $no_branch_limit + ? 0 + : C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; my $dbh = C4::Context->dbh; - my $sth = - $dbh->prepare( - "SELECT * - FROM categories - ORDER BY description" - ); - $sth->execute; - my $data = - $sth->fetchall_arrayref({}); + my $query = "SELECT categories.* FROM categories"; + $query .= qq{ + LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode + WHERE branchcode = ? OR branchcode IS NULL GROUP BY description + } if $branch_limit; + $query .= " ORDER BY description"; + my $sth = $dbh->prepare( $query ); + $sth->execute( $branch_limit ? $branch_limit : () ); + my $data = $sth->fetchall_arrayref( {} ); + $sth->finish; return $data; } # sub getborrowercategory @@ -1575,51 +1744,6 @@ sub GetAge{ return $age; } # sub get_age -=head2 get_institutions - - $insitutions = get_institutions(); - -Just returns a list of all the borrowers of type I, borrownumber and name - -=cut - -#' -sub get_institutions { - my $dbh = C4::Context->dbh(); - my $sth = - $dbh->prepare( -"SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname" - ); - $sth->execute('I'); - my %orgs; - while ( my $data = $sth->fetchrow_hashref() ) { - $orgs{ $data->{'borrowernumber'} } = $data; - } - return ( \%orgs ); - -} # sub get_institutions - -=head2 add_member_orgs - - add_member_orgs($borrowernumber,$borrowernumbers); - -Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table - -=cut - -#' -sub add_member_orgs { - my ( $borrowernumber, $otherborrowers ) = @_; - my $dbh = C4::Context->dbh(); - my $query = - "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)"; - my $sth = $dbh->prepare($query); - foreach my $otherborrowernumber (@$otherborrowers) { - $sth->execute( $borrowernumber, $otherborrowernumber ); - } - -} # sub add_member_orgs - =head2 GetCities $cityarrayref = GetCities(); @@ -1747,7 +1871,9 @@ sub ExtendMemberSubscriptionTo { my $dbh = C4::Context->dbh; my $borrower = GetMember('borrowernumber'=>$borrowerid); unless ($date){ - $date=POSIX::strftime("%Y-%m-%d",localtime()); + $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ? + C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") : + C4::Dates->new()->output("iso"); $date = GetExpiryDate( $borrower->{'categorycode'}, $date ); } my $sth = $dbh->do(<prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?"); - $sth->execute($borrower->{'categorycode'}); - my ($enrolmentfee) = $sth->fetchrow; - if ($enrolmentfee && $enrolmentfee > 0) { - # insert fee in patron debts - manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee); - } - return $date if ($sth); - return 0; -} - -=head2 GetRoadTypes (OUEST-PROVENCE) - - ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes(); - -Looks up the different road type . Returns two -elements: a reference-to-array, which lists the id_roadtype -codes, and a reference-to-hash, which maps the road type of the road . -=cut - -sub GetRoadTypes { - my $dbh = C4::Context->dbh; - my $query = qq| -SELECT roadtypeid,road_type -FROM roadtype -ORDER BY road_type|; - my $sth = $dbh->prepare($query); - $sth->execute(); - my %roadtype; - my @id; - - # insert empty value to create a empty choice in cgi popup - - while ( my $data = $sth->fetchrow_hashref ) { - - push @id, $data->{'roadtypeid'}; - $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'}; - } + AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} ); -#test to know if the table contain some records if no the function return nothing - my $id = @id; - if ( $id eq 0 ) { - return (); - } - else { - unshift( @id, "" ); - return ( \@id, \%roadtype ); - } + logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog"); + return $date if ($sth); + return 0; } - - =head2 GetTitles (OUEST-PROVENCE) ($borrowertitle)= &GetTitles(); @@ -1831,19 +1911,19 @@ sub GetTitles { =head2 GetPatronImage - my ($imagedata, $dberror) = GetPatronImage($cardnumber); + my ($imagedata, $dberror) = GetPatronImage($borrowernumber); -Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber. +Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber. =cut sub GetPatronImage { - my ($cardnumber) = @_; - warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug; + my ($borrowernumber) = @_; + warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug; my $dbh = C4::Context->dbh; - my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?'; + my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?'; my $sth = $dbh->prepare($query); - $sth->execute($cardnumber); + $sth->execute($borrowernumber); my $imagedata = $sth->fetchrow_hashref; warn "Database error!" if $sth->errstr; return $imagedata, $sth->errstr; @@ -1862,7 +1942,7 @@ sub PutPatronImage { my ($cardnumber, $mimetype, $imgfile) = @_; warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug; my $dbh = C4::Context->dbh; - my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;"; + my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;"; my $sth = $dbh->prepare($query); $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile); warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr; @@ -1871,19 +1951,19 @@ sub PutPatronImage { =head2 RmPatronImage - my ($dberror) = RmPatronImage($cardnumber); + my ($dberror) = RmPatronImage($borrowernumber); -Removes the image for the patron with the supplied cardnumber. +Removes the image for the patron with the supplied borrowernumber. =cut sub RmPatronImage { - my ($cardnumber) = @_; - warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug; + my ($borrowernumber) = @_; + warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug; my $dbh = C4::Context->dbh; - my $query = "DELETE FROM patronimage WHERE cardnumber = ?;"; + my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;"; my $sth = $dbh->prepare($query); - $sth->execute($cardnumber); + $sth->execute($borrowernumber); my $dberror = $sth->errstr; warn "Database error!" if $sth->errstr; return $dberror; @@ -1908,75 +1988,65 @@ sub GetHideLostItemsPreference { return $hidelostitems; } -=head2 GetRoadTypeDetails (OUEST-PROVENCE) +=head2 GetBorrowersToExpunge - ($roadtype) = &GetRoadTypeDetails($roadtypeid); + $borrowers = &GetBorrowersToExpunge( + not_borrowered_since => $not_borrowered_since, + expired_before => $expired_before, + category_code => $category_code, + branchcode => $branchcode + ); -Returns the description of roadtype -C<&$roadtype>return description of road type -C<&$roadtypeid>this is the value of roadtype s + This function get all borrowers based on the given criteria. =cut -sub GetRoadTypeDetails { - my ($roadtypeid) = @_; - my $dbh = C4::Context->dbh; - my $query = qq| -SELECT road_type -FROM roadtype -WHERE roadtypeid=?|; - my $sth = $dbh->prepare($query); - $sth->execute($roadtypeid); - my $roadtype = $sth->fetchrow; - return ($roadtype); -} - -=head2 GetBorrowersWhoHaveNotBorrowedSince - - &GetBorrowersWhoHaveNotBorrowedSince($date) - -this function get all borrowers who haven't borrowed since the date given on input arg. +sub GetBorrowersToExpunge { + my $params = shift; -=cut - -sub GetBorrowersWhoHaveNotBorrowedSince { - my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime()); - my $filterexpiry = shift; - my $filterbranch = shift || - ((C4::Context->preference('IndependantBranches') + my $filterdate = $params->{'not_borrowered_since'}; + my $filterexpiry = $params->{'expired_before'}; + my $filtercategory = $params->{'category_code'}; + my $filterbranch = $params->{'branchcode'} || + ((C4::Context->preference('IndependentBranches') && C4::Context->userenv - && C4::Context->userenv->{flags} % 2 !=1 + && !C4::Context->IsSuperLibrarian() && C4::Context->userenv->{branch}) ? C4::Context->userenv->{branch} : ""); + my $dbh = C4::Context->dbh; my $query = " SELECT borrowers.borrowernumber, - max(old_issues.timestamp) as latestissue, - max(issues.timestamp) as currentissue + MAX(old_issues.timestamp) AS latestissue, + MAX(issues.timestamp) AS currentissue FROM borrowers JOIN categories USING (categorycode) LEFT JOIN old_issues USING (borrowernumber) LEFT JOIN issues USING (borrowernumber) WHERE category_type <> 'S' - AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0) + AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0) "; my @query_params; - if ($filterbranch && $filterbranch ne ""){ - $query.=" AND borrowers.branchcode= ?"; - push @query_params,$filterbranch; + if ( $filterbranch && $filterbranch ne "" ) { + $query.= " AND borrowers.branchcode = ? "; + push( @query_params, $filterbranch ); } - if($filterexpiry){ + if ( $filterexpiry ) { $query .= " AND dateexpiry < ? "; - push @query_params,$filterdate; + push( @query_params, $filterexpiry ); + } + if ( $filtercategory ) { + $query .= " AND categorycode = ? "; + push( @query_params, $filtercategory ); } - $query.=" GROUP BY borrowers.borrowernumber"; - if ($filterdate){ - $query.=" HAVING (latestissue < ? OR latestissue IS NULL) - AND currentissue IS NULL"; + $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL "; + if ( $filterdate ) { + $query.=" AND ( latestissue < ? OR latestissue IS NULL ) "; push @query_params,$filterdate; } warn $query if $debug; + my $sth = $dbh->prepare($query); if (scalar(@query_params)>0){ $sth->execute(@query_params); @@ -2004,9 +2074,9 @@ I<$result> is a ref to an array which all elements are a hasref. sub GetBorrowersWhoHaveNeverBorrowed { my $filterbranch = shift || - ((C4::Context->preference('IndependantBranches') + ((C4::Context->preference('IndependentBranches') && C4::Context->userenv - && C4::Context->userenv->{flags} % 2 !=1 + && !C4::Context->IsSuperLibrarian() && C4::Context->userenv->{branch}) ? C4::Context->userenv->{branch} : ""); @@ -2054,9 +2124,9 @@ sub GetBorrowersWithIssuesHistoryOlderThan { my $dbh = C4::Context->dbh; my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime()); my $filterbranch = shift || - ((C4::Context->preference('IndependantBranches') + ((C4::Context->preference('IndependentBranches') && C4::Context->userenv - && C4::Context->userenv->{flags} % 2 !=1 + && !C4::Context->IsSuperLibrarian() && C4::Context->userenv->{branch}) ? C4::Context->userenv->{branch} : ""); @@ -2110,29 +2180,6 @@ sub GetBorrowersNamesAndLatestIssue { return $results; } -=head2 DebarMember - - my $success = DebarMember( $borrowernumber ); - -marks a Member as debarred, and therefore unable to checkout any more -items. - -return : -true on success, false on failure - -=cut - -sub DebarMember { - my $borrowernumber = shift; - - return unless defined $borrowernumber; - return unless $borrowernumber =~ /^\d+$/; - - return ModMember( borrowernumber => $borrowernumber, - debarred => 1 ); - -} - =head2 ModPrivacy =over 4 @@ -2182,7 +2229,7 @@ sub AddMessage { my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )"; my $sth = $dbh->prepare($query); $sth->execute( $borrowernumber, $branchcode, $message_type, $message ); - + logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog"); return 1; } @@ -2272,11 +2319,174 @@ sub DeleteMessage { my ( $message_id ) = @_; my $dbh = C4::Context->dbh; - - my $query = "DELETE FROM messages WHERE message_id = ?"; + my $query = "SELECT * FROM messages WHERE message_id = ?"; my $sth = $dbh->prepare($query); $sth->execute( $message_id ); + my $message = $sth->fetchrow_hashref(); + $query = "DELETE FROM messages WHERE message_id = ?"; + $sth = $dbh->prepare($query); + $sth->execute( $message_id ); + logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog"); +} + +=head2 IssueSlip + + IssueSlip($branchcode, $borrowernumber, $quickslip) + + Returns letter hash ( see C4::Letters::GetPreparedLetter ) + + $quickslip is boolean, to indicate whether we want a quick slip + +=cut + +sub IssueSlip { + my ($branch, $borrowernumber, $quickslip) = @_; + +# return unless ( C4::Context->boolean_preference('printcirculationslips') ); + + my $now = POSIX::strftime("%Y-%m-%d", localtime); + + my $issueslist = GetPendingIssues($borrowernumber); + foreach my $it (@$issueslist){ + if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) { + $it->{'now'} = 1; + } + elsif ((substr $it->{'date_due'}, 0, 10) le $now) { + $it->{'overdue'} = 1; + } + my $dt = dt_from_string( $it->{'date_due'} ); + $it->{'date_due'} = output_pref( $dt );; + } + my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist; + + my ($letter_code, %repeat); + if ( $quickslip ) { + $letter_code = 'ISSUEQSLIP'; + %repeat = ( + 'checkedout' => [ map { + 'biblio' => $_, + 'items' => $_, + 'issues' => $_, + }, grep { $_->{'now'} } @issues ], + ); + } + else { + $letter_code = 'ISSUESLIP'; + %repeat = ( + 'checkedout' => [ map { + 'biblio' => $_, + 'items' => $_, + 'issues' => $_, + }, grep { !$_->{'overdue'} } @issues ], + + 'overdue' => [ map { + 'biblio' => $_, + 'items' => $_, + 'issues' => $_, + }, grep { $_->{'overdue'} } @issues ], + + 'news' => [ map { + $_->{'timestamp'} = $_->{'newdate'}; + { opac_news => $_ } + } @{ GetNewsToDisplay("slip",$branch) } ], + ); + } + + return C4::Letters::GetPreparedLetter ( + module => 'circulation', + letter_code => $letter_code, + branchcode => $branch, + tables => { + 'branches' => $branch, + 'borrowers' => $borrowernumber, + }, + repeat => \%repeat, + ); +} + +=head2 GetBorrowersWithEmail + + ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com'); + +This gets a list of users and their basic details from their email address. +As it's possible for multiple user to have the same email address, it provides +you with all of them. If there is no userid for the user, there will be an +C there. An empty list will be returned if there are no matches. + +=cut + +sub GetBorrowersWithEmail { + my $email = shift; + + my $dbh = C4::Context->dbh; + + my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?"; + my $sth=$dbh->prepare($query); + $sth->execute($email); + my @result = (); + while (my $ref = $sth->fetch) { + push @result, $ref; + } + die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err; + return @result; +} + +sub AddMember_Opac { + my ( %borrower ) = @_; + + $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory'); + + my $sr = new String::Random; + $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ]; + my $password = $sr->randpattern("AAAAAAAAAA"); + $borrower{'password'} = $password; + + $borrower{'cardnumber'} = fixup_cardnumber(); + + my $borrowernumber = AddMember(%borrower); + + return ( $borrowernumber, $password ); +} + +=head2 AddEnrolmentFeeIfNeeded + + AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} ); + +Add enrolment fee for a patron if needed. + +=cut + +sub AddEnrolmentFeeIfNeeded { + my ( $categorycode, $borrowernumber ) = @_; + # check for enrollment fee & add it if needed + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare(q{ + SELECT enrolmentfee + FROM categories + WHERE categorycode=? + }); + $sth->execute( $categorycode ); + if ( $sth->err ) { + warn sprintf('Database returned the following error: %s', $sth->errstr); + return; + } + my ($enrolmentfee) = $sth->fetchrow; + if ($enrolmentfee && $enrolmentfee > 0) { + # insert fee in patron debts + C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee ); + } +} + +sub HasOverdues { + my ( $borrowernumber ) = @_; + + my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?"; + my $sth = C4::Context->dbh->prepare( $sql ); + $sth->execute( $borrowernumber ); + my ( $count ) = $sth->fetchrow_array(); + + return $count; } END { } # module clean-up code here (global destructor)