3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
24 #use warnings; FIXME - Bug 2505
26 use String
::Random
qw( random_string );
27 use Scalar
::Util
qw( looks_like_number );
28 use Date
::Calc qw
/Today check_date Date_to_Days/;
29 use C4
::Log
; # logaction
35 use C4
::Members
::Attributes
qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
36 use C4
::NewsChannels
; #get slip news
40 use Text
::Unaccent
qw( unac_string );
41 use Koha
::AuthUtils
qw(hash_password);
44 use Koha
::List
::Patron
;
46 use Koha
::Patron
::Categories
;
48 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
50 use Module
::Load
::Conditional
qw( can_load );
51 if ( ! can_load
( modules
=> { 'Koha::NorwegianPatronDB' => undef } ) ) {
52 $debug && warn "Unable to load Koha::NorwegianPatronDB";
57 $debug = $ENV{DEBUG
} || 0;
66 &GetMemberIssuesAndFines
70 &GetFirstValidEmailAddress
71 &GetNoticeEmailAddress
76 &GetHideLostItemsPreference
79 &GetMemberAccountRecords
80 &GetBorNotifyAcctRecord
82 GetBorrowerCategorycode
84 &GetBorrowersToExpunge
85 &GetBorrowersWhoHaveNeverBorrowed
86 &GetBorrowersWithIssuesHistoryOlderThan
88 &GetUpcomingMembershipExpires
127 C4::Members - Perl Module containing convenience functions for member handling
135 This module contains routines for adding, modifying and deleting members/patrons/borrowers
139 =head2 GetMemberDetails
141 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
143 Looks up a patron and returns information about him or her. If
144 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
145 up the borrower by number; otherwise, it looks up the borrower by card
148 C<$borrower> is a reference-to-hash whose keys are the fields of the
149 borrowers table in the Koha database. In addition,
150 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
151 about the patron. Its keys act as flags :
153 if $borrower->{flags}->{LOST} {
154 # Patron's card was reported lost
157 If the state of a flag means that the patron should not be
158 allowed to borrow any more books, then it will have a C<noissues> key
161 See patronflags for more details.
163 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
164 about the top-level permissions flags set for the borrower. For example,
165 if a user has the "editcatalogue" permission,
166 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
171 sub GetMemberDetails
{
172 my ( $borrowernumber, $cardnumber ) = @_;
173 my $dbh = C4
::Context
->dbh;
176 if ($borrowernumber) {
177 $sth = $dbh->prepare("
180 categories.description,
181 categories.BlockExpiredPatronOpacActions,
185 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
186 WHERE borrowernumber = ?
188 $sth->execute($borrowernumber);
190 elsif ($cardnumber) {
191 $sth = $dbh->prepare("
194 categories.description,
195 categories.BlockExpiredPatronOpacActions,
199 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
202 $sth->execute($cardnumber);
207 my $borrower = $sth->fetchrow_hashref;
208 return unless $borrower;
209 my ($amount) = GetMemberAccountRecords
($borrower->{borrowernumber
});
210 $borrower->{'amountoutstanding'} = $amount;
211 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
212 my $flags = patronflags
( $borrower);
215 $sth = $dbh->prepare("select bit,flag from userflags");
217 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
218 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
219 $accessflagshash->{$flag} = 1;
222 $borrower->{'flags'} = $flags;
223 $borrower->{'authflags'} = $accessflagshash;
225 # Handle setting the true behavior for BlockExpiredPatronOpacActions
226 $borrower->{'BlockExpiredPatronOpacActions'} =
227 C4
::Context
->preference('BlockExpiredPatronOpacActions')
228 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
230 $borrower->{'is_expired'} = 0;
231 $borrower->{'is_expired'} = 1 if
232 defined($borrower->{dateexpiry
}) &&
233 $borrower->{'dateexpiry'} ne '0000-00-00' &&
234 Date_to_Days
( Today
() ) >
235 Date_to_Days
( split /-/, $borrower->{'dateexpiry'} );
237 return ($borrower); #, $flags, $accessflagshash);
242 $flags = &patronflags($patron);
244 This function is not exported.
246 The following will be set where applicable:
247 $flags->{CHARGES}->{amount} Amount of debt
248 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
249 $flags->{CHARGES}->{message} Message -- deprecated
251 $flags->{CREDITS}->{amount} Amount of credit
252 $flags->{CREDITS}->{message} Message -- deprecated
254 $flags->{ GNA } Patron has no valid address
255 $flags->{ GNA }->{noissues} Set for each GNA
256 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
258 $flags->{ LOST } Patron's card reported lost
259 $flags->{ LOST }->{noissues} Set for each LOST
260 $flags->{ LOST }->{message} Message -- deprecated
262 $flags->{DBARRED} Set if patron debarred, no access
263 $flags->{DBARRED}->{noissues} Set for each DBARRED
264 $flags->{DBARRED}->{message} Message -- deprecated
267 $flags->{ NOTES }->{message} The note itself. NOT deprecated
269 $flags->{ ODUES } Set if patron has overdue books.
270 $flags->{ ODUES }->{message} "Yes" -- deprecated
271 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
272 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
274 $flags->{WAITING} Set if any of patron's reserves are available
275 $flags->{WAITING}->{message} Message -- deprecated
276 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
280 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
281 overdue items. Its elements are references-to-hash, each describing an
282 overdue item. The keys are selected fields from the issues, biblio,
283 biblioitems, and items tables of the Koha database.
285 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
286 the overdue items, one per line. Deprecated.
288 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
289 available items. Each element is a reference-to-hash whose keys are
290 fields from the reserves table of the Koha database.
294 All the "message" fields that include language generated in this function are deprecated,
295 because such strings belong properly in the display layer.
297 The "message" field that comes from the DB is OK.
301 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
302 # FIXME rename this function.
305 my ( $patroninformation) = @_;
306 my $dbh=C4
::Context
->dbh;
307 my ($balance, $owing) = GetMemberAccountBalance
( $patroninformation->{'borrowernumber'});
310 my $noissuescharge = C4
::Context
->preference("noissuescharge") || 5;
311 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
312 $flaginfo{'amount'} = sprintf "%.02f", $owing;
313 if ( $owing > $noissuescharge && !C4
::Context
->preference("AllowFineOverride") ) {
314 $flaginfo{'noissues'} = 1;
316 $flags{'CHARGES'} = \
%flaginfo;
318 elsif ( $balance < 0 ) {
320 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
321 $flaginfo{'amount'} = sprintf "%.02f", $balance;
322 $flags{'CREDITS'} = \
%flaginfo;
325 # Check the debt of the guarntees of this patron
326 my $no_issues_charge_guarantees = C4
::Context
->preference("NoIssuesChargeGuarantees");
327 $no_issues_charge_guarantees = undef unless looks_like_number
( $no_issues_charge_guarantees );
328 if ( defined $no_issues_charge_guarantees ) {
329 my $p = Koha
::Patrons
->find( $patroninformation->{borrowernumber
} );
330 my @guarantees = $p->guarantees();
331 my $guarantees_non_issues_charges;
332 foreach my $g ( @guarantees ) {
333 my ( $b, $n, $o ) = C4
::Members
::GetMemberAccountBalance
( $g->id );
334 $guarantees_non_issues_charges += $n;
337 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
339 $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
340 $flaginfo{'amount'} = $guarantees_non_issues_charges;
341 $flaginfo{'noissues'} = 1 unless C4
::Context
->preference("allowfineoverride");
342 $flags{'CHARGES_GUARANTEES'} = \
%flaginfo;
346 if ( $patroninformation->{'gonenoaddress'}
347 && $patroninformation->{'gonenoaddress'} == 1 )
350 $flaginfo{'message'} = 'Borrower has no valid address.';
351 $flaginfo{'noissues'} = 1;
352 $flags{'GNA'} = \
%flaginfo;
354 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
356 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
357 $flaginfo{'noissues'} = 1;
358 $flags{'LOST'} = \
%flaginfo;
360 if ( $patroninformation->{'debarred'} && check_date
( split( /-/, $patroninformation->{'debarred'} ) ) ) {
361 if ( Date_to_Days
(Date
::Calc
::Today
) < Date_to_Days
( split( /-/, $patroninformation->{'debarred'} ) ) ) {
363 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
364 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
365 $flaginfo{'noissues'} = 1;
366 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
367 $flags{'DBARRED'} = \
%flaginfo;
370 if ( $patroninformation->{'borrowernotes'}
371 && $patroninformation->{'borrowernotes'} )
374 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
375 $flags{'NOTES'} = \
%flaginfo;
377 my ( $odues, $itemsoverdue ) = C4
::Overdues
::checkoverdues
($patroninformation->{'borrowernumber'});
378 if ( $odues && $odues > 0 ) {
380 $flaginfo{'message'} = "Yes";
381 $flaginfo{'itemlist'} = $itemsoverdue;
382 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
385 $flaginfo{'itemlisttext'} .=
386 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
388 $flags{'ODUES'} = \
%flaginfo;
390 my @itemswaiting = C4
::Reserves
::GetReservesFromBorrowernumber
( $patroninformation->{'borrowernumber'},'W' );
391 my $nowaiting = scalar @itemswaiting;
392 if ( $nowaiting > 0 ) {
394 $flaginfo{'message'} = "Reserved items available";
395 $flaginfo{'itemlist'} = \
@itemswaiting;
396 $flags{'WAITING'} = \
%flaginfo;
404 $borrower = &GetMember(%information);
406 Retrieve the first patron record meeting on criteria listed in the
407 C<%information> hash, which should contain one or more
408 pairs of borrowers column names and values, e.g.,
410 $borrower = GetMember(borrowernumber => id);
412 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
413 the C<borrowers> table in the Koha database.
415 FIXME: GetMember() is used throughout the code as a lookup
416 on a unique key such as the borrowernumber, but this meaning is not
417 enforced in the routine itself.
423 my ( %information ) = @_;
424 if (exists $information{borrowernumber
} && !defined $information{borrowernumber
}) {
425 #passing mysql's kohaadmin?? Makes no sense as a query
428 my $dbh = C4
::Context
->dbh;
430 q{SELECT borrowers.*, categories.category_type, categories.description
432 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
435 for (keys %information ) {
443 if (defined $information{$_}) {
445 push @values, $information{$_};
448 $select .= "$_ IS NULL";
451 $debug && warn $select, " ",values %information;
452 my $sth = $dbh->prepare("$select");
453 $sth->execute(@values);
454 my $data = $sth->fetchall_arrayref({});
455 #FIXME interface to this routine now allows generation of a result set
456 #so whole array should be returned but bowhere in the current code expects this
464 =head2 IsMemberBlocked
466 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
468 Returns whether a patron is restricted or has overdue items that may result
469 in a block of circulation privileges.
471 C<$block_status> can have the following values:
473 1 if the patron is currently restricted, in which case
474 C<$count> is the expiration date (9999-12-31 for indefinite)
476 -1 if the patron has overdue items, in which case C<$count> is the number of them
478 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
480 Existing active restrictions are checked before current overdue items.
484 sub IsMemberBlocked
{
485 my $borrowernumber = shift;
486 my $dbh = C4
::Context
->dbh;
488 my $blockeddate = Koha
::Patrons
->find( $borrowernumber )->is_debarred;
490 return ( 1, $blockeddate ) if $blockeddate;
492 # if he have late issues
493 my $sth = $dbh->prepare(
494 "SELECT COUNT(*) as latedocs
496 WHERE borrowernumber = ?
497 AND date_due < now()"
499 $sth->execute($borrowernumber);
500 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
502 return ( -1, $latedocs ) if $latedocs > 0;
507 =head2 GetMemberIssuesAndFines
509 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
511 Returns aggregate data about items borrowed by the patron with the
512 given borrowernumber.
514 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
515 number of overdue items the patron currently has borrowed. C<$issue_count> is the
516 number of books the patron currently has borrowed. C<$total_fines> is
517 the total fine currently due by the borrower.
522 sub GetMemberIssuesAndFines
{
523 my ( $borrowernumber ) = @_;
524 my $dbh = C4
::Context
->dbh;
525 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
527 $debug and warn $query."\n";
528 my $sth = $dbh->prepare($query);
529 $sth->execute($borrowernumber);
530 my $issue_count = $sth->fetchrow_arrayref->[0];
532 $sth = $dbh->prepare(
533 "SELECT COUNT(*) FROM issues
534 WHERE borrowernumber = ?
535 AND date_due < now()"
537 $sth->execute($borrowernumber);
538 my $overdue_count = $sth->fetchrow_arrayref->[0];
540 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
541 $sth->execute($borrowernumber);
542 my $total_fines = $sth->fetchrow_arrayref->[0];
544 return ($overdue_count, $issue_count, $total_fines);
550 my $success = ModMember(borrowernumber => $borrowernumber,
551 [ field => value ]... );
553 Modify borrower's data. All date fields should ALREADY be in ISO format.
556 true on success, or false on failure
562 # test to know if you must update or not the borrower password
563 if (exists $data{password
}) {
564 if ($data{password
} eq '****' or $data{password
} eq '') {
565 delete $data{password
};
567 if ( C4
::Context
->preference('NorwegianPatronDBEnable') && C4
::Context
->preference('NorwegianPatronDBEnable') == 1 ) {
568 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
569 Koha
::NorwegianPatronDB
::NLUpdateHashedPIN
( $data{'borrowernumber'}, $data{password
} );
571 $data{password
} = hash_password
($data{password
});
575 my $old_categorycode = GetBorrowerCategorycode
( $data{borrowernumber
} );
577 # get only the columns of a borrower
578 my $schema = Koha
::Database
->new()->schema;
579 my @columns = $schema->source('Borrower')->columns;
580 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ?
( $_ => $data{$_} ) : () } keys(%data) };
581 delete $new_borrower->{flags
};
583 $new_borrower->{dateofbirth
} ||= undef if exists $new_borrower->{dateofbirth
};
584 $new_borrower->{dateenrolled
} ||= undef if exists $new_borrower->{dateenrolled
};
585 $new_borrower->{dateexpiry
} ||= undef if exists $new_borrower->{dateexpiry
};
586 $new_borrower->{debarred
} ||= undef if exists $new_borrower->{debarred
};
587 $new_borrower->{sms_provider_id
} ||= undef if exists $new_borrower->{sms_provider_id
};
589 my $rs = $schema->resultset('Borrower')->search({
590 borrowernumber
=> $new_borrower->{borrowernumber
},
593 delete $new_borrower->{userid
} if exists $new_borrower->{userid
} and not $new_borrower->{userid
};
595 my $execute_success = $rs->update($new_borrower);
596 if ($execute_success ne '0E0') { # only proceed if the update was a success
597 # If the patron changes to a category with enrollment fee, we add a fee
598 if ( $data{categorycode
} and $data{categorycode
} ne $old_categorycode ) {
599 if ( C4
::Context
->preference('FeeOnChangePatronCategory') ) {
600 AddEnrolmentFeeIfNeeded
( $data{categorycode
}, $data{borrowernumber
} );
604 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
605 # cronjob will use for syncing with NL
606 if ( C4
::Context
->preference('NorwegianPatronDBEnable') && C4
::Context
->preference('NorwegianPatronDBEnable') == 1 ) {
607 my $borrowersync = Koha
::Database
->new->schema->resultset('BorrowerSync')->find({
608 'synctype' => 'norwegianpatrondb',
609 'borrowernumber' => $data{'borrowernumber'}
611 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
612 # we can sync as changed. And the "new sync" will pick up all changes since
613 # the patron was created anyway.
614 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
615 $borrowersync->update( { 'syncstatus' => 'edited' } );
617 # Set the value of 'sync'
618 $borrowersync->update( { 'sync' => $data{'sync'} } );
619 # Try to do the live sync
620 Koha
::NorwegianPatronDB
::NLSync
({ 'borrowernumber' => $data{'borrowernumber'} });
623 logaction
("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4
::Context
->preference("BorrowersLog");
625 return $execute_success;
630 $borrowernumber = &AddMember(%borrower);
632 insert new borrower into table
634 (%borrower keys are database columns. Database columns could be
635 different in different versions. Please look into database for correct
638 Returns the borrowernumber upon success
640 Returns as undef upon any db error without further processing
647 my $dbh = C4
::Context
->dbh;
648 my $schema = Koha
::Database
->new()->schema;
650 # generate a proper login if none provided
651 $data{'userid'} = Generate_Userid
( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
652 if ( $data{'userid'} eq '' || !Check_Userid
( $data{'userid'} ) );
654 # add expiration date if it isn't already there
655 $data{dateexpiry
} ||= Koha
::Patron
::Categories
->find( $data{categorycode
} )->get_expiry_date;
657 # add enrollment date if it isn't already there
658 unless ( $data{'dateenrolled'} ) {
659 $data{'dateenrolled'} = output_pref
( { dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' } );
662 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
664 $patron_category->default_privacy() eq 'default' ?
1
665 : $patron_category->default_privacy() eq 'never' ?
2
666 : $patron_category->default_privacy() eq 'forever' ?
0
669 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
671 # Make a copy of the plain text password for later use
672 my $plain_text_password = $data{'password'};
674 # create a disabled account if no password provided
675 $data{'password'} = ($data{'password'})? hash_password
($data{'password'}) : '!';
677 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
678 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
679 $data{'debarred'} = undef if ( not $data{'debarred'} );
680 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
682 # get only the columns of Borrower
683 my @columns = $schema->source('Borrower')->columns;
684 my $new_member = { map { join(' ',@columns) =~ /$_/ ?
( $_ => $data{$_} ) : () } keys(%data) } ;
685 $new_member->{checkprevcheckout
} ||= 'inherit';
686 delete $new_member->{borrowernumber
};
688 my $rs = $schema->resultset('Borrower');
689 $data{borrowernumber
} = $rs->create($new_member)->id;
691 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
692 # cronjob will use for syncing with NL
693 if ( exists $data{'borrowernumber'} && C4
::Context
->preference('NorwegianPatronDBEnable') && C4
::Context
->preference('NorwegianPatronDBEnable') == 1 ) {
694 Koha
::Database
->new->schema->resultset('BorrowerSync')->create({
695 'borrowernumber' => $data{'borrowernumber'},
696 'synctype' => 'norwegianpatrondb',
698 'syncstatus' => 'new',
699 'hashed_pin' => Koha
::NorwegianPatronDB
::NLEncryptPIN
( $plain_text_password ),
703 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
704 logaction
("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4
::Context
->preference("BorrowersLog");
706 AddEnrolmentFeeIfNeeded
( $data{categorycode
}, $data{borrowernumber
} );
708 return $data{borrowernumber
};
713 my $uniqueness = Check_Userid($userid,$borrowernumber);
715 $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 != '').
717 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.
720 0 for not unique (i.e. this $userid already exists)
721 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
726 my ( $uid, $borrowernumber ) = @_;
728 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
730 return 0 if ( $uid eq C4
::Context
->config('user') );
732 my $rs = Koha
::Database
->new()->schema()->resultset('Borrower');
735 $params->{userid
} = $uid;
736 $params->{borrowernumber
} = { '!=' => $borrowernumber } if ($borrowernumber);
738 my $count = $rs->count( $params );
740 return $count ?
0 : 1;
743 =head2 Generate_Userid
745 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
747 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
749 $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.
752 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).
756 sub Generate_Userid
{
757 my ($borrowernumber, $firstname, $surname) = @_;
760 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
762 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
763 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
764 $newuid = lc(($firstname)?
"$firstname.$surname" : $surname);
765 $newuid = unac_string
('utf-8',$newuid);
766 $newuid .= $offset unless $offset == 0;
769 } while (!Check_Userid
($newuid,$borrowernumber));
774 =head2 fixup_cardnumber
776 Warning: The caller is responsible for locking the members table in write
777 mode, to avoid database corruption.
781 use vars
qw( @weightings );
782 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
784 sub fixup_cardnumber {
785 my ($cardnumber) = @_;
786 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
788 # Find out whether member numbers should be generated
789 # automatically. Should be either "1" or something else.
790 # Defaults to "0", which is interpreted as "no".
792 # if ($cardnumber !~ /\S/ && $autonumber_members) {
793 ($autonumber_members) or return $cardnumber;
794 my $checkdigit = C4::Context->preference('checkdigit');
795 my $dbh = C4::Context->dbh;
796 if ( $checkdigit and $checkdigit eq 'katipo' ) {
798 # if checkdigit is selected, calculate katipo-style cardnumber.
799 # otherwise, just use the max()
800 # purpose: generate checksum'd member numbers.
801 # We'll assume we just got the max value of digits 2-8 of member #'s
802 # from the database and our job is to increment that by one,
803 # determine the 1st and 9th digits and return the full string.
804 my $sth = $dbh->prepare(
805 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
808 my $data = $sth->fetchrow_hashref;
809 $cardnumber = $data->{new_num};
810 if ( !$cardnumber ) { # If DB has no values,
811 $cardnumber = 1000000; # start at 1000000
817 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
818 # read weightings, left to right, 1 char at a time
819 my $temp1 = $weightings[$i];
821 # sequence left to right, 1 char at a time
822 my $temp2 = substr( $cardnumber, $i, 1 );
824 # mult each char 1-7 by its corresponding weighting
825 $sum += $temp1 * $temp2;
828 my $rem = ( $sum % 11 );
829 $rem = 'X' if $rem == 10;
831 return "V$cardnumber$rem";
834 my $sth = $dbh->prepare(
835 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
838 my ($result) = $sth->fetchrow;
841 return $cardnumber; # just here as a fallback/reminder
844 =head2 GetPendingIssues
846 my $issues = &GetPendingIssues(@borrowernumber);
848 Looks up what the patron with the given borrowernumber has borrowed.
850 C<&GetPendingIssues> returns a
851 reference-to-array where each element is a reference-to-hash; the
852 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
853 The keys include C<biblioitems> fields except marc and marcxml.
857 sub GetPendingIssues {
858 my @borrowernumbers = @_;
860 unless (@borrowernumbers ) { # return a ref_to_array
861 return \@borrowernumbers; # to not cause surprise to caller
864 # Borrowers part of the query
866 for (my $i = 0; $i < @borrowernumbers; $i++) {
867 $bquery .= ' issues.borrowernumber = ?';
868 if ($i < $#borrowernumbers ) {
873 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
874 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
875 # FIXME: circ/ciculation.pl tries to sort by timestamp!
876 # FIXME: namespace collision: other collisions possible.
877 # FIXME: most of this data isn't really being used by callers.
884 biblioitems.itemtype,
887 biblioitems.publicationyear,
888 biblioitems.publishercode,
889 biblioitems.volumedate,
890 biblioitems.volumedesc,
895 borrowers.cardnumber,
896 issues.timestamp AS timestamp,
897 issues.renewals AS renewals,
898 issues.borrowernumber AS borrowernumber,
899 items.renewals AS totalrenewals
901 LEFT JOIN items ON items.itemnumber = issues.itemnumber
902 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
903 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
904 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
907 ORDER BY issues.issuedate"
910 my $sth = C4::Context->dbh->prepare($query);
911 $sth->execute(@borrowernumbers);
912 my $data = $sth->fetchall_arrayref({});
913 my $today = dt_from_string;
915 if ($_->{issuedate}) {
916 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
918 $_->{date_due_sql} = $_->{date_due};
919 # FIXME no need to have this value
920 $_->{date_due} or next;
921 $_->{date_due_sql} = $_->{date_due};
922 # FIXME no need to have this value
923 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
924 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
933 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
935 Looks up what the patron with the given borrowernumber has borrowed,
936 and sorts the results.
938 C<$sortkey> is the name of a field on which to sort the results. This
939 should be the name of a field in the C<issues>, C<biblio>,
940 C<biblioitems>, or C<items> table in the Koha database.
942 C<$limit> is the maximum number of results to return.
944 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
945 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
946 C<items> tables of the Koha database.
952 my ( $borrowernumber, $order, $limit ) = @_;
954 return unless $borrowernumber;
955 $order = 'date_due desc' unless $order;
957 my $dbh = C4::Context->dbh;
959 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
961 LEFT JOIN items on items.itemnumber=issues.itemnumber
962 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
963 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
964 WHERE borrowernumber=?
966 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
968 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
969 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
970 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
971 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
974 $query .= " limit $limit";
977 my $sth = $dbh->prepare($query);
978 $sth->execute( $borrowernumber, $borrowernumber );
979 return $sth->fetchall_arrayref( {} );
983 =head2 GetMemberAccountRecords
985 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
987 Looks up accounting data for the patron with the given borrowernumber.
989 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
990 reference-to-array, where each element is a reference-to-hash; the
991 keys are the fields of the C<accountlines> table in the Koha database.
992 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
993 total amount outstanding for all of the account lines.
997 sub GetMemberAccountRecords {
998 my ($borrowernumber) = @_;
999 my $dbh = C4::Context->dbh;
1005 WHERE borrowernumber=?);
1006 $strsth.=" ORDER BY accountlines_id desc";
1007 my $sth= $dbh->prepare( $strsth );
1008 $sth->execute( $borrowernumber );
1011 while ( my $data = $sth->fetchrow_hashref ) {
1012 if ( $data->{itemnumber} ) {
1013 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1014 $data->{biblionumber} = $biblio->{biblionumber};
1015 $data->{title} = $biblio->{title};
1017 $acctlines[$numlines] = $data;
1019 $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1022 return ( $total, \@acctlines,$numlines);
1025 =head2 GetMemberAccountBalance
1027 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1029 Calculates amount immediately owing by the patron - non-issue charges.
1030 Based on GetMemberAccountRecords.
1031 Charges exempt from non-issue are:
1033 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1034 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1038 sub GetMemberAccountBalance {
1039 my ($borrowernumber) = @_;
1041 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1044 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1045 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1046 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1047 my $dbh = C4::Context->dbh;
1048 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1049 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1051 my %not_fine = map {$_ => 1} @not_fines;
1053 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1054 my $other_charges = 0;
1055 foreach (@$acctlines) {
1056 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1059 return ( $total, $total - $other_charges, $other_charges);
1062 =head2 GetBorNotifyAcctRecord
1064 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1066 Looks up accounting data for the patron with the given borrowernumber per file number.
1068 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1069 reference-to-array, where each element is a reference-to-hash; the
1070 keys are the fields of the C<accountlines> table in the Koha database.
1071 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1072 total amount outstanding for all of the account lines.
1076 sub GetBorNotifyAcctRecord {
1077 my ( $borrowernumber, $notifyid ) = @_;
1078 my $dbh = C4::Context->dbh;
1081 my $sth = $dbh->prepare(
1084 WHERE borrowernumber=?
1086 AND amountoutstanding != '0'
1087 ORDER BY notify_id,accounttype
1090 $sth->execute( $borrowernumber, $notifyid );
1092 while ( my $data = $sth->fetchrow_hashref ) {
1093 if ( $data->{itemnumber} ) {
1094 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1095 $data->{biblionumber} = $biblio->{biblionumber};
1096 $data->{title} = $biblio->{title};
1098 $acctlines[$numlines] = $data;
1100 $total += int(100 * $data->{'amountoutstanding'});
1103 return ( $total, \@acctlines, $numlines );
1106 sub checkcardnumber {
1107 my ( $cardnumber, $borrowernumber ) = @_;
1109 # If cardnumber is null, we assume they're allowed.
1110 return 0 unless defined $cardnumber;
1112 my $dbh = C4::Context->dbh;
1113 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1114 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1115 my $sth = $dbh->prepare($query);
1118 ( $borrowernumber ? $borrowernumber : () )
1121 return 1 if $sth->fetchrow_hashref;
1123 my ( $min_length, $max_length ) = get_cardnumber_length();
1125 if length $cardnumber > $max_length
1126 or length $cardnumber < $min_length;
1131 =head2 get_cardnumber_length
1133 my ($min, $max) = C4::Members::get_cardnumber_length()
1135 Returns the minimum and maximum length for patron cardnumbers as
1136 determined by the CardnumberLength system preference, the
1137 BorrowerMandatoryField system preference, and the width of the
1142 sub get_cardnumber_length {
1143 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1144 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1145 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1146 # Is integer and length match
1147 if ( $cardnumber_length =~ m|^\d+$| ) {
1148 $min = $max = $cardnumber_length
1149 if $cardnumber_length >= $min
1150 and $cardnumber_length <= $max;
1152 # Else assuming it is a range
1153 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1154 $min = $1 if $1 and $min < $1;
1155 $max = $2 if $2 and $max > $2;
1159 return ( $min, $max );
1162 =head2 GetFirstValidEmailAddress
1164 $email = GetFirstValidEmailAddress($borrowernumber);
1166 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1167 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1172 sub GetFirstValidEmailAddress {
1173 my $borrowernumber = shift;
1174 my $dbh = C4::Context->dbh;
1175 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1176 $sth->execute( $borrowernumber );
1177 my $data = $sth->fetchrow_hashref;
1179 if ($data->{'email'}) {
1180 return $data->{'email'};
1181 } elsif ($data->{'emailpro'}) {
1182 return $data->{'emailpro'};
1183 } elsif ($data->{'B_email'}) {
1184 return $data->{'B_email'};
1190 =head2 GetNoticeEmailAddress
1192 $email = GetNoticeEmailAddress($borrowernumber);
1194 Return the email address of borrower used for notices, given the borrowernumber.
1195 Returns the empty string if no email address.
1199 sub GetNoticeEmailAddress {
1200 my $borrowernumber = shift;
1202 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1203 # if syspref is set to 'first valid' (value == OFF), look up email address
1204 if ( $which_address eq 'OFF' ) {
1205 return GetFirstValidEmailAddress($borrowernumber);
1207 # specified email address field
1208 my $dbh = C4::Context->dbh;
1209 my $sth = $dbh->prepare( qq{
1210 SELECT $which_address AS primaryemail
1212 WHERE borrowernumber=?
1214 $sth->execute($borrowernumber);
1215 my $data = $sth->fetchrow_hashref;
1216 return $data->{'primaryemail'} || '';
1219 =head2 GetUpcomingMembershipExpires
1221 my $expires = GetUpcomingMembershipExpires({
1222 branch => $branch, before => $before, after => $after,
1225 $branch is an optional branch code.
1226 $before/$after is an optional number of days before/after the date that
1227 is set by the preference MembershipExpiryDaysNotice.
1228 If the pref would be 14, before 2 and after 3, you will get all expires
1233 sub GetUpcomingMembershipExpires {
1234 my ( $params ) = @_;
1235 my $before = $params->{before} || 0;
1236 my $after = $params->{after} || 0;
1237 my $branch = $params->{branch};
1239 my $dbh = C4::Context->dbh;
1240 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1241 my $date1 = dt_from_string->add( days => $days - $before );
1242 my $date2 = dt_from_string->add( days => $days + $after );
1243 $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1244 $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1247 SELECT borrowers.*, categories.description,
1248 branches.branchname, branches.branchemail FROM borrowers
1249 LEFT JOIN branches USING (branchcode)
1250 LEFT JOIN categories USING (categorycode)
1253 $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1255 $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1258 my $sth = $dbh->prepare( $query );
1259 my @pars = $branch? ( $branch ): ();
1260 push @pars, $date1, $date2;
1261 $sth->execute( @pars );
1262 my $results = $sth->fetchall_arrayref( {} );
1266 =head2 GetBorrowerCategorycode
1268 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1270 Given the borrowernumber, the function returns the corresponding categorycode
1274 sub GetBorrowerCategorycode {
1275 my ( $borrowernumber ) = @_;
1276 my $dbh = C4::Context->dbh;
1277 my $sth = $dbh->prepare( qq{
1280 WHERE borrowernumber = ?
1282 $sth->execute( $borrowernumber );
1283 return $sth->fetchrow;
1288 $dateofbirth,$date = &GetAge($date);
1290 this function return the borrowers age with the value of dateofbirth
1296 my ( $date, $date_ref ) = @_;
1298 if ( not defined $date_ref ) {
1299 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1302 my ( $year1, $month1, $day1 ) = split /-/, $date;
1303 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1305 my $age = $year2 - $year1;
1306 if ( $month1 . $day1 > $month2 . $day2 ) {
1315 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1316 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1317 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1319 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1320 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1322 This function sets the borrower's dateofbirth to match the given age.
1323 Optionally relative to the given $datetime_reference.
1325 @PARAM1 koha.borrowers-object
1326 @PARAM2 DateTime::Duration-object as the desired age
1327 OR a ISO 8601 Date. (To make the API more pleasant)
1328 @PARAM3 DateTime-object as the relative date, defaults to now().
1329 RETURNS The given borrower reference @PARAM1.
1330 DIES If there was an error with the ISO Date handling.
1336 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1337 $datetime_ref = DateTime->now() unless $datetime_ref;
1339 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1340 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1341 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1344 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1348 my $new_datetime_ref = $datetime_ref->clone();
1349 $new_datetime_ref->subtract_duration( $datetimeduration );
1351 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1356 =head2 MoveMemberToDeleted
1358 $result = &MoveMemberToDeleted($borrowernumber);
1360 Copy the record from borrowers to deletedborrowers table.
1361 The routine returns 1 for success, undef for failure.
1365 sub MoveMemberToDeleted {
1366 my ($member) = shift or return;
1368 my $schema = Koha::Database->new()->schema();
1369 my $borrowers_rs = $schema->resultset('Borrower');
1370 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1371 my $borrower = $borrowers_rs->find($member);
1372 return unless $borrower;
1374 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1376 return $deleted ? 1 : undef;
1381 DelMember($borrowernumber);
1383 This function remove directly a borrower whitout writing it on deleteborrower.
1384 + Deletes reserves for the borrower
1389 my $dbh = C4::Context->dbh;
1390 my $borrowernumber = shift;
1391 #warn "in delmember with $borrowernumber";
1392 return unless $borrowernumber; # borrowernumber is mandatory.
1393 # Delete Patron's holds
1394 my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1395 $_->delete for @holds;
1400 WHERE borrowernumber = ?
1402 my $sth = $dbh->prepare($query);
1403 $sth->execute($borrowernumber);
1404 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1408 =head2 HandleDelBorrower
1410 HandleDelBorrower($borrower);
1412 When a member is deleted (DelMember in Members.pm), you should call me first.
1413 This routine deletes/moves lists and entries for the deleted member/borrower.
1414 Lists owned by the borrower are deleted, but entries from the borrower to
1415 other lists are kept.
1419 sub HandleDelBorrower {
1422 my $dbh = C4::Context->dbh;
1424 #Delete all lists and all shares of this borrower
1425 #Consistent with the approach Koha uses on deleting individual lists
1426 #Note that entries in virtualshelfcontents added by this borrower to
1427 #lists of others will be handled by a table constraint: the borrower
1428 #is set to NULL in those entries.
1429 $query="DELETE FROM virtualshelves WHERE owner=?";
1430 $dbh->do($query,undef,($borrower));
1433 #We could handle the above deletes via a constraint too.
1434 #But a new BZ report 11889 has been opened to discuss another approach.
1435 #Instead of deleting we could also disown lists (based on a pref).
1436 #In that way we could save shared and public lists.
1437 #The current table constraints support that idea now.
1438 #This pref should then govern the results of other routines/methods such as
1439 #Koha::Virtualshelf->new->delete too.
1442 =head2 GetHideLostItemsPreference
1444 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1446 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1447 C<&$hidelostitemspref>return value of function, 0 or 1
1451 sub GetHideLostItemsPreference {
1452 my ($borrowernumber) = @_;
1453 my $dbh = C4::Context->dbh;
1454 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1455 my $sth = $dbh->prepare($query);
1456 $sth->execute($borrowernumber);
1457 my $hidelostitems = $sth->fetchrow;
1458 return $hidelostitems;
1461 =head2 GetBorrowersToExpunge
1463 $borrowers = &GetBorrowersToExpunge(
1464 not_borrowed_since => $not_borrowed_since,
1465 expired_before => $expired_before,
1466 category_code => $category_code,
1467 patron_list_id => $patron_list_id,
1468 branchcode => $branchcode
1471 This function get all borrowers based on the given criteria.
1475 sub GetBorrowersToExpunge {
1478 my $filterdate = $params->{'not_borrowed_since'};
1479 my $filterexpiry = $params->{'expired_before'};
1480 my $filtercategory = $params->{'category_code'};
1481 my $filterbranch = $params->{'branchcode'} ||
1482 ((C4::Context->preference('IndependentBranches')
1483 && C4::Context->userenv
1484 && !C4::Context->IsSuperLibrarian()
1485 && C4::Context->userenv->{branch})
1486 ? C4::Context->userenv->{branch}
1488 my $filterpatronlist = $params->{'patron_list_id'};
1490 my $dbh = C4::Context->dbh;
1492 SELECT borrowers.borrowernumber,
1493 MAX(old_issues.timestamp) AS latestissue,
1494 MAX(issues.timestamp) AS currentissue
1496 JOIN categories USING (categorycode)
1500 WHERE guarantorid IS NOT NULL
1501 AND guarantorid <> 0
1502 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1503 LEFT JOIN old_issues USING (borrowernumber)
1504 LEFT JOIN issues USING (borrowernumber)|;
1505 if ( $filterpatronlist ){
1506 $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1508 $query .= q| WHERE category_type <> 'S'
1509 AND tmp.guarantorid IS NULL
1512 if ( $filterbranch && $filterbranch ne "" ) {
1513 $query.= " AND borrowers.branchcode = ? ";
1514 push( @query_params, $filterbranch );
1516 if ( $filterexpiry ) {
1517 $query .= " AND dateexpiry < ? ";
1518 push( @query_params, $filterexpiry );
1520 if ( $filtercategory ) {
1521 $query .= " AND categorycode = ? ";
1522 push( @query_params, $filtercategory );
1524 if ( $filterpatronlist ){
1525 $query.=" AND patron_list_id = ? ";
1526 push( @query_params, $filterpatronlist );
1528 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1529 if ( $filterdate ) {
1530 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1531 push @query_params,$filterdate;
1533 warn $query if $debug;
1535 my $sth = $dbh->prepare($query);
1536 if (scalar(@query_params)>0){
1537 $sth->execute(@query_params);
1544 while ( my $data = $sth->fetchrow_hashref ) {
1545 push @results, $data;
1550 =head2 GetBorrowersWhoHaveNeverBorrowed
1552 $results = &GetBorrowersWhoHaveNeverBorrowed
1554 This function get all borrowers who have never borrowed.
1556 I<$result> is a ref to an array which all elements are a hasref.
1560 sub GetBorrowersWhoHaveNeverBorrowed {
1561 my $filterbranch = shift ||
1562 ((C4::Context->preference('IndependentBranches')
1563 && C4::Context->userenv
1564 && !C4::Context->IsSuperLibrarian()
1565 && C4::Context->userenv->{branch})
1566 ? C4::Context->userenv->{branch}
1568 my $dbh = C4::Context->dbh;
1570 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1572 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1573 WHERE issues.borrowernumber IS NULL
1576 if ($filterbranch && $filterbranch ne ""){
1577 $query.=" AND borrowers.branchcode= ?";
1578 push @query_params,$filterbranch;
1580 warn $query if $debug;
1582 my $sth = $dbh->prepare($query);
1583 if (scalar(@query_params)>0){
1584 $sth->execute(@query_params);
1591 while ( my $data = $sth->fetchrow_hashref ) {
1592 push @results, $data;
1597 =head2 GetBorrowersWithIssuesHistoryOlderThan
1599 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1601 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1603 I<$result> is a ref to an array which all elements are a hashref.
1604 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1608 sub GetBorrowersWithIssuesHistoryOlderThan {
1609 my $dbh = C4::Context->dbh;
1610 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1611 my $filterbranch = shift ||
1612 ((C4::Context->preference('IndependentBranches')
1613 && C4::Context->userenv
1614 && !C4::Context->IsSuperLibrarian()
1615 && C4::Context->userenv->{branch})
1616 ? C4::Context->userenv->{branch}
1619 SELECT count(borrowernumber) as n,borrowernumber
1621 WHERE returndate < ?
1622 AND borrowernumber IS NOT NULL
1625 push @query_params, $date;
1627 $query.=" AND branchcode = ?";
1628 push @query_params, $filterbranch;
1630 $query.=" GROUP BY borrowernumber ";
1631 warn $query if $debug;
1632 my $sth = $dbh->prepare($query);
1633 $sth->execute(@query_params);
1636 while ( my $data = $sth->fetchrow_hashref ) {
1637 push @results, $data;
1644 IssueSlip($branchcode, $borrowernumber, $quickslip)
1646 Returns letter hash ( see C4::Letters::GetPreparedLetter )
1648 $quickslip is boolean, to indicate whether we want a quick slip
1650 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1686 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1691 my ($branch, $borrowernumber, $quickslip) = @_;
1693 # FIXME Check callers before removing this statement
1694 #return unless $borrowernumber;
1696 my @issues = @{ GetPendingIssues($borrowernumber) };
1698 for my $issue (@issues) {
1699 $issue->{date_due} = $issue->{date_due_sql};
1701 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1702 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1703 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1709 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1711 my $s = $b->{timestamp} <=> $a->{timestamp};
1713 $b->{issuedate} <=> $a->{issuedate} : $s;
1716 my ($letter_code, %repeat);
1718 $letter_code = 'ISSUEQSLIP';
1720 'checkedout' => [ map {
1723 'biblioitems' => $_,
1725 }, grep { $_->{'now
'} } @issues ],
1729 $letter_code = 'ISSUESLIP
';
1731 'checkedout
' => [ map {
1734 'biblioitems
' => $_,
1736 }, grep { !$_->{'overdue
'} } @issues ],
1738 'overdue
' => [ map {
1741 'biblioitems
' => $_,
1743 }, grep { $_->{'overdue
'} } @issues ],
1746 $_->{'timestamp
'} = $_->{'newdate
'};
1748 } @{ GetNewsToDisplay("slip",$branch) } ],
1752 return C4::Letters::GetPreparedLetter (
1753 module => 'circulation
',
1754 letter_code => $letter_code,
1755 branchcode => $branch,
1757 'branches
' => $branch,
1758 'borrowers
' => $borrowernumber,
1764 =head2 GetBorrowersWithEmail
1766 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me
@example.com
');
1768 This gets a list of users and their basic details from their email address.
1769 As it's possible
for multiple user to have the same email address
, it provides
1770 you with all of them
. If there is
no userid
for the user
, there will be an
1771 C
<undef> there
. An empty list will be returned
if there are
no matches
.
1775 sub GetBorrowersWithEmail
{
1778 my $dbh = C4
::Context
->dbh;
1780 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
1781 my $sth=$dbh->prepare($query);
1782 $sth->execute($email);
1784 while (my $ref = $sth->fetch) {
1787 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
1791 =head2 AddMember_Opac
1795 sub AddMember_Opac
{
1796 my ( %borrower ) = @_;
1798 $borrower{'categorycode'} //= C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
1799 if (not defined $borrower{'password'}){
1800 my $sr = new String
::Random
;
1801 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1802 my $password = $sr->randpattern("AAAAAAAAAA");
1803 $borrower{'password'} = $password;
1806 $borrower{'cardnumber'} = fixup_cardnumber
( $borrower{'cardnumber'} );
1808 my $borrowernumber = AddMember
(%borrower);
1810 return ( $borrowernumber, $borrower{'password'} );
1813 =head2 AddEnrolmentFeeIfNeeded
1815 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1817 Add enrolment fee for a patron if needed.
1821 sub AddEnrolmentFeeIfNeeded
{
1822 my ( $categorycode, $borrowernumber ) = @_;
1823 # check for enrollment fee & add it if needed
1824 my $dbh = C4
::Context
->dbh;
1825 my $sth = $dbh->prepare(q{
1828 WHERE categorycode=?
1830 $sth->execute( $categorycode );
1832 warn sprintf('Database returned the following error: %s', $sth->errstr);
1835 my ($enrolmentfee) = $sth->fetchrow;
1836 if ($enrolmentfee && $enrolmentfee > 0) {
1837 # insert fee in patron debts
1838 C4
::Accounts
::manualinvoice
( $borrowernumber, '', '', 'A', $enrolmentfee );
1842 =head2 DeleteExpiredOpacRegistrations
1844 Delete accounts that haven't been upgraded from the 'temporary' category
1845 Returns the number of removed patrons
1849 sub DeleteExpiredOpacRegistrations
{
1851 my $delay = C4
::Context
->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1852 my $category_code = C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
1854 return 0 if not $category_code or not defined $delay or $delay eq q
||;
1857 SELECT borrowernumber
1859 WHERE categorycode
= ? AND DATEDIFF
( NOW
(), dateenrolled
) > ?
|;
1861 my $dbh = C4
::Context
->dbh;
1862 my $sth = $dbh->prepare($query);
1863 $sth->execute( $category_code, $delay );
1865 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1866 DelMember
($borrowernumber);
1872 =head2 DeleteUnverifiedOpacRegistrations
1874 Delete all unverified self registrations in borrower_modifications,
1875 older than the specified number of days.
1879 sub DeleteUnverifiedOpacRegistrations
{
1881 my $dbh = C4
::Context
->dbh;
1883 DELETE FROM borrower_modifications
1884 WHERE borrowernumber
= 0 AND DATEDIFF
( NOW
(), timestamp
) > ?
|;
1885 my $cnt=$dbh->do($sql, undef, ($days) );
1886 return $cnt eq '0E0'?
0: $cnt;
1889 sub GetOverduesForPatron
{
1890 my ( $borrowernumber ) = @_;
1894 FROM issues, items, biblio, biblioitems
1895 WHERE items.itemnumber=issues.itemnumber
1896 AND biblio.biblionumber = items.biblionumber
1897 AND biblio.biblionumber = biblioitems.biblionumber
1898 AND issues.borrowernumber = ?
1899 AND date_due < NOW()
1902 my $sth = C4
::Context
->dbh->prepare( $sql );
1903 $sth->execute( $borrowernumber );
1905 return $sth->fetchall_arrayref({});
1908 END { } # module clean-up code here (global destructor)