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
78 &GetMemberAccountRecords
79 &GetBorNotifyAcctRecord
81 &GetBorrowersToExpunge
82 &GetBorrowersWhoHaveNeverBorrowed
83 &GetBorrowersWithIssuesHistoryOlderThan
85 &GetUpcomingMembershipExpires
118 C4::Members - Perl Module containing convenience functions for member handling
126 This module contains routines for adding, modifying and deleting members/patrons/borrowers
130 =head2 GetMemberDetails
132 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
134 Looks up a patron and returns information about him or her. If
135 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
136 up the borrower by number; otherwise, it looks up the borrower by card
139 C<$borrower> is a reference-to-hash whose keys are the fields of the
140 borrowers table in the Koha database. In addition,
141 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
142 about the patron. Its keys act as flags :
144 if $borrower->{flags}->{LOST} {
145 # Patron's card was reported lost
148 If the state of a flag means that the patron should not be
149 allowed to borrow any more books, then it will have a C<noissues> key
152 See patronflags for more details.
154 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
155 about the top-level permissions flags set for the borrower. For example,
156 if a user has the "editcatalogue" permission,
157 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
162 sub GetMemberDetails {
163 my ( $borrowernumber, $cardnumber ) = @_;
164 my $dbh = C4::Context->dbh;
167 if ($borrowernumber) {
168 $sth = $dbh->prepare("
171 categories.description,
172 categories.BlockExpiredPatronOpacActions,
176 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
177 WHERE borrowernumber = ?
179 $sth->execute($borrowernumber);
181 elsif ($cardnumber) {
182 $sth = $dbh->prepare("
185 categories.description,
186 categories.BlockExpiredPatronOpacActions,
190 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
193 $sth->execute($cardnumber);
198 my $borrower = $sth->fetchrow_hashref;
199 return unless $borrower;
200 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
201 $borrower->{'amountoutstanding'} = $amount;
202 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
203 my $flags = patronflags( $borrower);
206 $sth = $dbh->prepare("select bit,flag from userflags");
208 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
209 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
210 $accessflagshash->{$flag} = 1;
213 $borrower->{'flags'} = $flags;
214 $borrower->{'authflags'} = $accessflagshash;
216 # Handle setting the true behavior for BlockExpiredPatronOpacActions
217 $borrower->{'BlockExpiredPatronOpacActions'} =
218 C4::Context->preference('BlockExpiredPatronOpacActions')
219 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
221 $borrower->{'is_expired'} = 0;
222 $borrower->{'is_expired'} = 1 if
223 defined($borrower->{dateexpiry}) &&
224 $borrower->{'dateexpiry'} ne '0000-00-00' &&
225 Date_to_Days( Today() ) >
226 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
228 return ($borrower); #, $flags, $accessflagshash);
233 $flags = &patronflags($patron);
235 This function is not exported.
237 The following will be set where applicable:
238 $flags->{CHARGES}->{amount} Amount of debt
239 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
240 $flags->{CHARGES}->{message} Message -- deprecated
242 $flags->{CREDITS}->{amount} Amount of credit
243 $flags->{CREDITS}->{message} Message -- deprecated
245 $flags->{ GNA } Patron has no valid address
246 $flags->{ GNA }->{noissues} Set for each GNA
247 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
249 $flags->{ LOST } Patron's card reported lost
250 $flags->{ LOST }->{noissues} Set for each LOST
251 $flags->{ LOST }->{message} Message -- deprecated
253 $flags->{DBARRED} Set if patron debarred, no access
254 $flags->{DBARRED}->{noissues} Set for each DBARRED
255 $flags->{DBARRED}->{message} Message -- deprecated
258 $flags->{ NOTES }->{message} The note itself. NOT deprecated
260 $flags->{ ODUES } Set if patron has overdue books.
261 $flags->{ ODUES }->{message} "Yes" -- deprecated
262 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
263 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
265 $flags->{WAITING} Set if any of patron's reserves are available
266 $flags->{WAITING}->{message} Message -- deprecated
267 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
271 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
272 overdue items. Its elements are references-to-hash, each describing an
273 overdue item. The keys are selected fields from the issues, biblio,
274 biblioitems, and items tables of the Koha database.
276 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
277 the overdue items, one per line. Deprecated.
279 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
280 available items. Each element is a reference-to-hash whose keys are
281 fields from the reserves table of the Koha database.
285 All the "message" fields that include language generated in this function are deprecated,
286 because such strings belong properly in the display layer.
288 The "message" field that comes from the DB is OK.
292 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
293 # FIXME rename this function.
296 my ( $patroninformation) = @_;
297 my $dbh=C4::Context->dbh;
298 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
301 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
302 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
303 $flaginfo{'amount'} = sprintf "%.02f", $owing;
304 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
305 $flaginfo{'noissues'} = 1;
307 $flags{'CHARGES'} = \%flaginfo;
309 elsif ( $balance < 0 ) {
311 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
312 $flaginfo{'amount'} = sprintf "%.02f", $balance;
313 $flags{'CREDITS'} = \%flaginfo;
316 # Check the debt of the guarntees of this patron
317 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
318 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
319 if ( defined $no_issues_charge_guarantees ) {
320 my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
321 my @guarantees = $p->guarantees();
322 my $guarantees_non_issues_charges;
323 foreach my $g ( @guarantees ) {
324 my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
325 $guarantees_non_issues_charges += $n;
328 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
330 $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
331 $flaginfo{'amount'} = $guarantees_non_issues_charges;
332 $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
333 $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
337 if ( $patroninformation->{'gonenoaddress'}
338 && $patroninformation->{'gonenoaddress'} == 1 )
341 $flaginfo{'message'} = 'Borrower has no valid address.';
342 $flaginfo{'noissues'} = 1;
343 $flags{'GNA'} = \%flaginfo;
345 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
347 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
348 $flaginfo{'noissues'} = 1;
349 $flags{'LOST'} = \%flaginfo;
351 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
352 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
354 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
355 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
356 $flaginfo{'noissues'} = 1;
357 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
358 $flags{'DBARRED'} = \%flaginfo;
361 if ( $patroninformation->{'borrowernotes'}
362 && $patroninformation->{'borrowernotes'} )
365 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
366 $flags{'NOTES'} = \%flaginfo;
368 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
369 if ( $odues && $odues > 0 ) {
371 $flaginfo{'message'} = "Yes";
372 $flaginfo{'itemlist'} = $itemsoverdue;
373 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
376 $flaginfo{'itemlisttext'} .=
377 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
379 $flags{'ODUES'} = \%flaginfo;
381 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
382 my $nowaiting = scalar @itemswaiting;
383 if ( $nowaiting > 0 ) {
385 $flaginfo{'message'} = "Reserved items available";
386 $flaginfo{'itemlist'} = \@itemswaiting;
387 $flags{'WAITING'} = \%flaginfo;
395 $borrower = &GetMember(%information);
397 Retrieve the first patron record meeting on criteria listed in the
398 C<%information> hash, which should contain one or more
399 pairs of borrowers column names and values, e.g.,
401 $borrower = GetMember(borrowernumber => id);
403 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
404 the C<borrowers> table in the Koha database.
406 FIXME: GetMember() is used throughout the code as a lookup
407 on a unique key such as the borrowernumber, but this meaning is not
408 enforced in the routine itself.
414 my ( %information ) = @_;
415 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
416 #passing mysql's kohaadmin?? Makes no sense as a query
419 my $dbh = C4::Context->dbh;
421 q{SELECT borrowers.*, categories.category_type, categories.description
423 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
426 for (keys %information ) {
434 if (defined $information{$_}) {
436 push @values, $information{$_};
439 $select .= "$_ IS NULL";
442 $debug && warn $select, " ",values %information;
443 my $sth = $dbh->prepare("$select");
444 $sth->execute(@values);
445 my $data = $sth->fetchall_arrayref({});
446 #FIXME interface to this routine now allows generation of a result set
447 #so whole array should be returned but bowhere in the current code expects this
455 =head2 GetMemberIssuesAndFines
457 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
459 Returns aggregate data about items borrowed by the patron with the
460 given borrowernumber.
462 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
463 number of overdue items the patron currently has borrowed. C<$issue_count> is the
464 number of books the patron currently has borrowed. C<$total_fines> is
465 the total fine currently due by the borrower.
470 sub GetMemberIssuesAndFines {
471 my ( $borrowernumber ) = @_;
472 my $dbh = C4::Context->dbh;
473 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
475 $debug and warn $query."\n";
476 my $sth = $dbh->prepare($query);
477 $sth->execute($borrowernumber);
478 my $issue_count = $sth->fetchrow_arrayref->[0];
480 $sth = $dbh->prepare(
481 "SELECT COUNT(*) FROM issues
482 WHERE borrowernumber = ?
483 AND date_due < now()"
485 $sth->execute($borrowernumber);
486 my $overdue_count = $sth->fetchrow_arrayref->[0];
488 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
489 $sth->execute($borrowernumber);
490 my $total_fines = $sth->fetchrow_arrayref->[0];
492 return ($overdue_count, $issue_count, $total_fines);
498 my $success = ModMember(borrowernumber => $borrowernumber,
499 [ field => value ]... );
501 Modify borrower's data. All date fields should ALREADY be in ISO format.
504 true on success, or false on failure
510 # test to know if you must update or not the borrower password
511 if (exists $data{password}) {
512 if ($data{password} eq '****' or $data{password} eq '') {
513 delete $data{password};
515 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
516 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
517 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
519 $data{password} = hash_password($data{password});
523 my $old_categorycode = Koha::Patrons->find( $data{borrowernumber} )->categorycode;
525 # get only the columns of a borrower
526 my $schema = Koha::Database->new()->schema;
527 my @columns = $schema->source('Borrower')->columns;
528 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
529 delete $new_borrower->{flags};
531 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
532 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
533 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
534 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
535 $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
536 $new_borrower->{guarantorid} ||= undef if exists $new_borrower->{guarantorid};
538 my $patron = Koha::Patrons->find( $new_borrower->{borrowernumber} );
540 delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
542 my $execute_success = $patron->store if $patron->set($new_borrower);
544 if ($execute_success) { # only proceed if the update was a success
545 # If the patron changes to a category with enrollment fee, we add a fee
546 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
547 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
548 $patron->add_enrolment_fee_if_needed;
552 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
553 # cronjob will use for syncing with NL
554 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
555 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
556 'synctype' => 'norwegianpatrondb',
557 'borrowernumber' => $data{'borrowernumber'}
559 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
560 # we can sync as changed. And the "new sync" will pick up all changes since
561 # the patron was created anyway.
562 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
563 $borrowersync->update( { 'syncstatus' => 'edited' } );
565 # Set the value of 'sync'
566 $borrowersync->update( { 'sync' => $data{'sync'} } );
567 # Try to do the live sync
568 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
571 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
573 return $execute_success;
578 $borrowernumber = &AddMember(%borrower);
580 insert new borrower into table
582 (%borrower keys are database columns. Database columns could be
583 different in different versions. Please look into database for correct
586 Returns the borrowernumber upon success
588 Returns as undef upon any db error without further processing
595 my $dbh = C4::Context->dbh;
596 my $schema = Koha::Database->new()->schema;
598 # generate a proper login if none provided
599 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
600 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
602 # add expiration date if it isn't already there
603 $data{dateexpiry} ||= Koha::Patron::Categories->find( $data{categorycode} )->get_expiry_date;
605 # add enrollment date if it isn't already there
606 unless ( $data{'dateenrolled'} ) {
607 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
610 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
612 $patron_category->default_privacy() eq 'default' ? 1
613 : $patron_category->default_privacy() eq 'never' ? 2
614 : $patron_category->default_privacy() eq 'forever' ? 0
617 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
619 # Make a copy of the plain text password for later use
620 my $plain_text_password = $data{'password'};
622 # create a disabled account if no password provided
623 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
625 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
626 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
627 $data{'debarred'} = undef if ( not $data{'debarred'} );
628 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
630 # get only the columns of Borrower
631 # FIXME Do we really need this check?
632 my @columns = $schema->source('Borrower')->columns;
633 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
635 delete $new_member->{borrowernumber};
637 my $patron = Koha::Patron->new( $new_member )->store;
638 $data{borrowernumber} = $patron->borrowernumber;
640 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
641 # cronjob will use for syncing with NL
642 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
643 Koha::Database->new->schema->resultset('BorrowerSync')->create({
644 'borrowernumber' => $data{'borrowernumber'},
645 'synctype' => 'norwegianpatrondb',
647 'syncstatus' => 'new',
648 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
652 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
654 $patron->add_enrolment_fee_if_needed;
656 return $data{borrowernumber};
661 my $uniqueness = Check_Userid($userid,$borrowernumber);
663 $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 != '').
665 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.
668 0 for not unique (i.e. this $userid already exists)
669 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
674 my ( $uid, $borrowernumber ) = @_;
676 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
678 return 0 if ( $uid eq C4::Context->config('user') );
680 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
683 $params->{userid} = $uid;
684 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
686 my $count = $rs->count( $params );
688 return $count ? 0 : 1;
691 =head2 Generate_Userid
693 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
695 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
697 $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.
700 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).
704 sub Generate_Userid {
705 my ($borrowernumber, $firstname, $surname) = @_;
708 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
710 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
711 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
712 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
713 $newuid = unac_string('utf-8',$newuid);
714 $newuid .= $offset unless $offset == 0;
717 } while (!Check_Userid($newuid,$borrowernumber));
722 =head2 fixup_cardnumber
724 Warning: The caller is responsible for locking the members table in write
725 mode, to avoid database corruption.
729 use vars qw( @weightings );
730 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
732 sub fixup_cardnumber {
733 my ($cardnumber) = @_;
734 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
736 # Find out whether member numbers should be generated
737 # automatically. Should be either "1" or something else.
738 # Defaults to "0", which is interpreted as "no".
740 # if ($cardnumber !~ /\S/ && $autonumber_members) {
741 ($autonumber_members) or return $cardnumber;
742 my $checkdigit = C4::Context->preference('checkdigit');
743 my $dbh = C4::Context->dbh;
744 if ( $checkdigit and $checkdigit eq 'katipo' ) {
746 # if checkdigit is selected, calculate katipo-style cardnumber.
747 # otherwise, just use the max()
748 # purpose: generate checksum'd member numbers.
749 # We'll assume we just got the max value of digits 2-8 of member #'s
750 # from the database and our job is to increment that by one,
751 # determine the 1st and 9th digits and return the full string.
752 my $sth = $dbh->prepare(
753 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
756 my $data = $sth->fetchrow_hashref;
757 $cardnumber = $data->{new_num};
758 if ( !$cardnumber ) { # If DB has no values,
759 $cardnumber = 1000000; # start at 1000000
765 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
766 # read weightings, left to right, 1 char at a time
767 my $temp1 = $weightings[$i];
769 # sequence left to right, 1 char at a time
770 my $temp2 = substr( $cardnumber, $i, 1 );
772 # mult each char 1-7 by its corresponding weighting
773 $sum += $temp1 * $temp2;
776 my $rem = ( $sum % 11 );
777 $rem = 'X' if $rem == 10;
779 return "V$cardnumber$rem";
782 my $sth = $dbh->prepare(
783 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
786 my ($result) = $sth->fetchrow;
789 return $cardnumber; # just here as a fallback/reminder
792 =head2 GetPendingIssues
794 my $issues = &GetPendingIssues(@borrowernumber);
796 Looks up what the patron with the given borrowernumber has borrowed.
798 C<&GetPendingIssues> returns a
799 reference-to-array where each element is a reference-to-hash; the
800 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
801 The keys include C<biblioitems> fields except marc and marcxml.
805 sub GetPendingIssues {
806 my @borrowernumbers = @_;
808 unless (@borrowernumbers ) { # return a ref_to_array
809 return \@borrowernumbers; # to not cause surprise to caller
812 # Borrowers part of the query
814 for (my $i = 0; $i < @borrowernumbers; $i++) {
815 $bquery .= ' issues.borrowernumber = ?';
816 if ($i < $#borrowernumbers ) {
821 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
822 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
823 # FIXME: circ/ciculation.pl tries to sort by timestamp!
824 # FIXME: namespace collision: other collisions possible.
825 # FIXME: most of this data isn't really being used by callers.
832 biblioitems.itemtype,
835 biblioitems.publicationyear,
836 biblioitems.publishercode,
837 biblioitems.volumedate,
838 biblioitems.volumedesc,
843 borrowers.cardnumber,
844 issues.timestamp AS timestamp,
845 issues.renewals AS renewals,
846 issues.borrowernumber AS borrowernumber,
847 items.renewals AS totalrenewals
849 LEFT JOIN items ON items.itemnumber = issues.itemnumber
850 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
851 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
852 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
855 ORDER BY issues.issuedate"
858 my $sth = C4::Context->dbh->prepare($query);
859 $sth->execute(@borrowernumbers);
860 my $data = $sth->fetchall_arrayref({});
861 my $today = dt_from_string;
863 if ($_->{issuedate}) {
864 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
866 $_->{date_due_sql} = $_->{date_due};
867 # FIXME no need to have this value
868 $_->{date_due} or next;
869 $_->{date_due_sql} = $_->{date_due};
870 # FIXME no need to have this value
871 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
872 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
881 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
883 Looks up what the patron with the given borrowernumber has borrowed,
884 and sorts the results.
886 C<$sortkey> is the name of a field on which to sort the results. This
887 should be the name of a field in the C<issues>, C<biblio>,
888 C<biblioitems>, or C<items> table in the Koha database.
890 C<$limit> is the maximum number of results to return.
892 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
893 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
894 C<items> tables of the Koha database.
900 my ( $borrowernumber, $order, $limit ) = @_;
902 return unless $borrowernumber;
903 $order = 'date_due desc' unless $order;
905 my $dbh = C4::Context->dbh;
907 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
909 LEFT JOIN items on items.itemnumber=issues.itemnumber
910 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
911 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
912 WHERE borrowernumber=?
914 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
916 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
917 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
918 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
919 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
922 $query .= " limit $limit";
925 my $sth = $dbh->prepare($query);
926 $sth->execute( $borrowernumber, $borrowernumber );
927 return $sth->fetchall_arrayref( {} );
931 =head2 GetMemberAccountRecords
933 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
935 Looks up accounting data for the patron with the given borrowernumber.
937 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
938 reference-to-array, where each element is a reference-to-hash; the
939 keys are the fields of the C<accountlines> table in the Koha database.
940 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
941 total amount outstanding for all of the account lines.
945 sub GetMemberAccountRecords {
946 my ($borrowernumber) = @_;
947 my $dbh = C4::Context->dbh;
953 WHERE borrowernumber=?);
954 $strsth.=" ORDER BY accountlines_id desc";
955 my $sth= $dbh->prepare( $strsth );
956 $sth->execute( $borrowernumber );
959 while ( my $data = $sth->fetchrow_hashref ) {
960 if ( $data->{itemnumber} ) {
961 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
962 $data->{biblionumber} = $biblio->{biblionumber};
963 $data->{title} = $biblio->{title};
965 $acctlines[$numlines] = $data;
967 $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
970 return ( $total, \@acctlines,$numlines);
973 =head2 GetMemberAccountBalance
975 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
977 Calculates amount immediately owing by the patron - non-issue charges.
978 Based on GetMemberAccountRecords.
979 Charges exempt from non-issue are:
981 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
982 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
986 sub GetMemberAccountBalance {
987 my ($borrowernumber) = @_;
989 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
992 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
993 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
994 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
995 my $dbh = C4::Context->dbh;
996 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
997 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
999 my %not_fine = map {$_ => 1} @not_fines;
1001 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1002 my $other_charges = 0;
1003 foreach (@$acctlines) {
1004 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1007 return ( $total, $total - $other_charges, $other_charges);
1010 =head2 GetBorNotifyAcctRecord
1012 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1014 Looks up accounting data for the patron with the given borrowernumber per file number.
1016 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1017 reference-to-array, where each element is a reference-to-hash; the
1018 keys are the fields of the C<accountlines> table in the Koha database.
1019 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1020 total amount outstanding for all of the account lines.
1024 sub GetBorNotifyAcctRecord {
1025 my ( $borrowernumber, $notifyid ) = @_;
1026 my $dbh = C4::Context->dbh;
1029 my $sth = $dbh->prepare(
1032 WHERE borrowernumber=?
1034 AND amountoutstanding != '0'
1035 ORDER BY notify_id,accounttype
1038 $sth->execute( $borrowernumber, $notifyid );
1040 while ( my $data = $sth->fetchrow_hashref ) {
1041 if ( $data->{itemnumber} ) {
1042 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1043 $data->{biblionumber} = $biblio->{biblionumber};
1044 $data->{title} = $biblio->{title};
1046 $acctlines[$numlines] = $data;
1048 $total += int(100 * $data->{'amountoutstanding'});
1051 return ( $total, \@acctlines, $numlines );
1054 sub checkcardnumber {
1055 my ( $cardnumber, $borrowernumber ) = @_;
1057 # If cardnumber is null, we assume they're allowed.
1058 return 0 unless defined $cardnumber;
1060 my $dbh = C4::Context->dbh;
1061 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1062 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1063 my $sth = $dbh->prepare($query);
1066 ( $borrowernumber ? $borrowernumber : () )
1069 return 1 if $sth->fetchrow_hashref;
1071 my ( $min_length, $max_length ) = get_cardnumber_length();
1073 if length $cardnumber > $max_length
1074 or length $cardnumber < $min_length;
1079 =head2 get_cardnumber_length
1081 my ($min, $max) = C4::Members::get_cardnumber_length()
1083 Returns the minimum and maximum length for patron cardnumbers as
1084 determined by the CardnumberLength system preference, the
1085 BorrowerMandatoryField system preference, and the width of the
1090 sub get_cardnumber_length {
1091 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1092 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1093 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1094 # Is integer and length match
1095 if ( $cardnumber_length =~ m|^\d+$| ) {
1096 $min = $max = $cardnumber_length
1097 if $cardnumber_length >= $min
1098 and $cardnumber_length <= $max;
1100 # Else assuming it is a range
1101 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1102 $min = $1 if $1 and $min < $1;
1103 $max = $2 if $2 and $max > $2;
1107 return ( $min, $max );
1110 =head2 GetFirstValidEmailAddress
1112 $email = GetFirstValidEmailAddress($borrowernumber);
1114 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1115 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1120 sub GetFirstValidEmailAddress {
1121 my $borrowernumber = shift;
1122 my $dbh = C4::Context->dbh;
1123 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1124 $sth->execute( $borrowernumber );
1125 my $data = $sth->fetchrow_hashref;
1127 if ($data->{'email'}) {
1128 return $data->{'email'};
1129 } elsif ($data->{'emailpro'}) {
1130 return $data->{'emailpro'};
1131 } elsif ($data->{'B_email'}) {
1132 return $data->{'B_email'};
1138 =head2 GetNoticeEmailAddress
1140 $email = GetNoticeEmailAddress($borrowernumber);
1142 Return the email address of borrower used for notices, given the borrowernumber.
1143 Returns the empty string if no email address.
1147 sub GetNoticeEmailAddress {
1148 my $borrowernumber = shift;
1150 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1151 # if syspref is set to 'first valid' (value == OFF), look up email address
1152 if ( $which_address eq 'OFF' ) {
1153 return GetFirstValidEmailAddress($borrowernumber);
1155 # specified email address field
1156 my $dbh = C4::Context->dbh;
1157 my $sth = $dbh->prepare( qq{
1158 SELECT $which_address AS primaryemail
1160 WHERE borrowernumber=?
1162 $sth->execute($borrowernumber);
1163 my $data = $sth->fetchrow_hashref;
1164 return $data->{'primaryemail'} || '';
1167 =head2 GetUpcomingMembershipExpires
1169 my $expires = GetUpcomingMembershipExpires({
1170 branch => $branch, before => $before, after => $after,
1173 $branch is an optional branch code.
1174 $before/$after is an optional number of days before/after the date that
1175 is set by the preference MembershipExpiryDaysNotice.
1176 If the pref would be 14, before 2 and after 3, you will get all expires
1181 sub GetUpcomingMembershipExpires {
1182 my ( $params ) = @_;
1183 my $before = $params->{before} || 0;
1184 my $after = $params->{after} || 0;
1185 my $branch = $params->{branch};
1187 my $dbh = C4::Context->dbh;
1188 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1189 my $date1 = dt_from_string->add( days => $days - $before );
1190 my $date2 = dt_from_string->add( days => $days + $after );
1191 $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1192 $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1195 SELECT borrowers.*, categories.description,
1196 branches.branchname, branches.branchemail FROM borrowers
1197 LEFT JOIN branches USING (branchcode)
1198 LEFT JOIN categories USING (categorycode)
1201 $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1203 $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1206 my $sth = $dbh->prepare( $query );
1207 my @pars = $branch? ( $branch ): ();
1208 push @pars, $date1, $date2;
1209 $sth->execute( @pars );
1210 my $results = $sth->fetchall_arrayref( {} );
1216 $dateofbirth,$date = &GetAge($date);
1218 this function return the borrowers age with the value of dateofbirth
1224 my ( $date, $date_ref ) = @_;
1226 if ( not defined $date_ref ) {
1227 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1230 my ( $year1, $month1, $day1 ) = split /-/, $date;
1231 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1233 my $age = $year2 - $year1;
1234 if ( $month1 . $day1 > $month2 . $day2 ) {
1243 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1244 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1245 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1247 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1248 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1250 This function sets the borrower's dateofbirth to match the given age.
1251 Optionally relative to the given $datetime_reference.
1253 @PARAM1 koha.borrowers-object
1254 @PARAM2 DateTime::Duration-object as the desired age
1255 OR a ISO 8601 Date. (To make the API more pleasant)
1256 @PARAM3 DateTime-object as the relative date, defaults to now().
1257 RETURNS The given borrower reference @PARAM1.
1258 DIES If there was an error with the ISO Date handling.
1264 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1265 $datetime_ref = DateTime->now() unless $datetime_ref;
1267 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1268 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1269 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1272 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1276 my $new_datetime_ref = $datetime_ref->clone();
1277 $new_datetime_ref->subtract_duration( $datetimeduration );
1279 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1284 =head2 GetHideLostItemsPreference
1286 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1288 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1289 C<&$hidelostitemspref>return value of function, 0 or 1
1293 sub GetHideLostItemsPreference {
1294 my ($borrowernumber) = @_;
1295 my $dbh = C4::Context->dbh;
1296 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1297 my $sth = $dbh->prepare($query);
1298 $sth->execute($borrowernumber);
1299 my $hidelostitems = $sth->fetchrow;
1300 return $hidelostitems;
1303 =head2 GetBorrowersToExpunge
1305 $borrowers = &GetBorrowersToExpunge(
1306 not_borrowed_since => $not_borrowed_since,
1307 expired_before => $expired_before,
1308 category_code => $category_code,
1309 patron_list_id => $patron_list_id,
1310 branchcode => $branchcode
1313 This function get all borrowers based on the given criteria.
1317 sub GetBorrowersToExpunge {
1320 my $filterdate = $params->{'not_borrowed_since'};
1321 my $filterexpiry = $params->{'expired_before'};
1322 my $filterlastseen = $params->{'last_seen'};
1323 my $filtercategory = $params->{'category_code'};
1324 my $filterbranch = $params->{'branchcode'} ||
1325 ((C4::Context->preference('IndependentBranches')
1326 && C4::Context->userenv
1327 && !C4::Context->IsSuperLibrarian()
1328 && C4::Context->userenv->{branch})
1329 ? C4::Context->userenv->{branch}
1331 my $filterpatronlist = $params->{'patron_list_id'};
1333 my $dbh = C4::Context->dbh;
1335 SELECT borrowers.borrowernumber,
1336 MAX(old_issues.timestamp) AS latestissue,
1337 MAX(issues.timestamp) AS currentissue
1339 JOIN categories USING (categorycode)
1343 WHERE guarantorid IS NOT NULL
1344 AND guarantorid <> 0
1345 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1346 LEFT JOIN old_issues USING (borrowernumber)
1347 LEFT JOIN issues USING (borrowernumber)|;
1348 if ( $filterpatronlist ){
1349 $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1351 $query .= q| WHERE category_type <> 'S'
1352 AND tmp.guarantorid IS NULL
1355 if ( $filterbranch && $filterbranch ne "" ) {
1356 $query.= " AND borrowers.branchcode = ? ";
1357 push( @query_params, $filterbranch );
1359 if ( $filterexpiry ) {
1360 $query .= " AND dateexpiry < ? ";
1361 push( @query_params, $filterexpiry );
1363 if ( $filterlastseen ) {
1364 $query .= ' AND lastseen < ? ';
1365 push @query_params, $filterlastseen;
1367 if ( $filtercategory ) {
1368 $query .= " AND categorycode = ? ";
1369 push( @query_params, $filtercategory );
1371 if ( $filterpatronlist ){
1372 $query.=" AND patron_list_id = ? ";
1373 push( @query_params, $filterpatronlist );
1375 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1376 if ( $filterdate ) {
1377 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1378 push @query_params,$filterdate;
1380 warn $query if $debug;
1382 my $sth = $dbh->prepare($query);
1383 if (scalar(@query_params)>0){
1384 $sth->execute(@query_params);
1391 while ( my $data = $sth->fetchrow_hashref ) {
1392 push @results, $data;
1397 =head2 GetBorrowersWhoHaveNeverBorrowed
1399 $results = &GetBorrowersWhoHaveNeverBorrowed
1401 This function get all borrowers who have never borrowed.
1403 I<$result> is a ref to an array which all elements are a hasref.
1407 sub GetBorrowersWhoHaveNeverBorrowed {
1408 my $filterbranch = shift ||
1409 ((C4::Context->preference('IndependentBranches')
1410 && C4::Context->userenv
1411 && !C4::Context->IsSuperLibrarian()
1412 && C4::Context->userenv->{branch})
1413 ? C4::Context->userenv->{branch}
1415 my $dbh = C4::Context->dbh;
1417 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1419 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1420 WHERE issues.borrowernumber IS NULL
1423 if ($filterbranch && $filterbranch ne ""){
1424 $query.=" AND borrowers.branchcode= ?";
1425 push @query_params,$filterbranch;
1427 warn $query if $debug;
1429 my $sth = $dbh->prepare($query);
1430 if (scalar(@query_params)>0){
1431 $sth->execute(@query_params);
1438 while ( my $data = $sth->fetchrow_hashref ) {
1439 push @results, $data;
1444 =head2 GetBorrowersWithIssuesHistoryOlderThan
1446 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1448 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1450 I<$result> is a ref to an array which all elements are a hashref.
1451 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1455 sub GetBorrowersWithIssuesHistoryOlderThan {
1456 my $dbh = C4::Context->dbh;
1457 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1458 my $filterbranch = shift ||
1459 ((C4::Context->preference('IndependentBranches')
1460 && C4::Context->userenv
1461 && !C4::Context->IsSuperLibrarian()
1462 && C4::Context->userenv->{branch})
1463 ? C4::Context->userenv->{branch}
1466 SELECT count(borrowernumber) as n,borrowernumber
1468 WHERE returndate < ?
1469 AND borrowernumber IS NOT NULL
1472 push @query_params, $date;
1474 $query.=" AND branchcode = ?";
1475 push @query_params, $filterbranch;
1477 $query.=" GROUP BY borrowernumber ";
1478 warn $query if $debug;
1479 my $sth = $dbh->prepare($query);
1480 $sth->execute(@query_params);
1483 while ( my $data = $sth->fetchrow_hashref ) {
1484 push @results, $data;
1491 IssueSlip($branchcode, $borrowernumber, $quickslip)
1493 Returns letter hash ( see C4::Letters::GetPreparedLetter )
1495 $quickslip is boolean, to indicate whether we want a quick slip
1497 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1533 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1538 my ($branch, $borrowernumber, $quickslip) = @_;
1540 # FIXME Check callers before removing this statement
1541 #return unless $borrowernumber;
1543 my @issues = @{ GetPendingIssues($borrowernumber) };
1545 for my $issue (@issues) {
1546 $issue->{date_due} = $issue->{date_due_sql};
1548 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1549 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1550 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1556 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1558 my $s = $b->{timestamp} <=> $a->{timestamp};
1560 $b->{issuedate} <=> $a->{issuedate} : $s;
1563 my ($letter_code, %repeat);
1565 $letter_code = 'ISSUEQSLIP';
1567 'checkedout' => [ map {
1570 'biblioitems' => $_,
1572 }, grep { $_->{'now'} } @issues ],
1576 $letter_code = 'ISSUESLIP';
1578 'checkedout' => [ map {
1581 'biblioitems' => $_,
1583 }, grep { !$_->{'overdue'} } @issues ],
1585 'overdue' => [ map {
1588 'biblioitems' => $_,
1590 }, grep { $_->{'overdue'} } @issues ],
1593 $_->{'timestamp'} = $_->{'newdate'};
1595 } @{ GetNewsToDisplay("slip",$branch) } ],
1599 return C4::Letters::GetPreparedLetter (
1600 module => 'circulation',
1601 letter_code => $letter_code,
1602 branchcode => $branch,
1604 'branches' => $branch,
1605 'borrowers' => $borrowernumber,
1611 =head2 GetBorrowersWithEmail
1613 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
1615 This gets a list of users and their basic details from their email address.
1616 As it's possible for multiple user to have the same email address, it provides
1617 you with all of them. If there is no userid for the user, there will be an
1618 C<undef> there. An empty list will be returned if there are no matches.
1622 sub GetBorrowersWithEmail {
1625 my $dbh = C4::Context->dbh;
1627 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
1628 my $sth=$dbh->prepare($query);
1629 $sth->execute($email);
1631 while (my $ref = $sth->fetch) {
1634 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
1638 =head2 AddMember_Opac
1642 sub AddMember_Opac {
1643 my ( %borrower ) = @_;
1645 $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1646 if (not defined $borrower{'password'}){
1647 my $sr = new String::Random;
1648 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1649 my $password = $sr->randpattern("AAAAAAAAAA");
1650 $borrower{'password'} = $password;
1653 $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
1655 my $borrowernumber = AddMember(%borrower);
1657 return ( $borrowernumber, $borrower{'password'} );
1660 =head2 DeleteExpiredOpacRegistrations
1662 Delete accounts that haven't been upgraded from the 'temporary' category
1663 Returns the number of removed patrons
1667 sub DeleteExpiredOpacRegistrations {
1669 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1670 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1672 return 0 if not $category_code or not defined $delay or $delay eq q||;
1675 SELECT borrowernumber
1677 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
1679 my $dbh = C4::Context->dbh;
1680 my $sth = $dbh->prepare($query);
1681 $sth->execute( $category_code, $delay );
1683 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1684 Koha::Patrons->find($borrowernumber)->delete;
1690 =head2 DeleteUnverifiedOpacRegistrations
1692 Delete all unverified self registrations in borrower_modifications,
1693 older than the specified number of days.
1697 sub DeleteUnverifiedOpacRegistrations {
1699 my $dbh = C4::Context->dbh;
1701 DELETE FROM borrower_modifications
1702 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
1703 my $cnt=$dbh->do($sql, undef, ($days) );
1704 return $cnt eq '0E0'? 0: $cnt;
1707 sub GetOverduesForPatron {
1708 my ( $borrowernumber ) = @_;
1712 FROM issues, items, biblio, biblioitems
1713 WHERE items.itemnumber=issues.itemnumber
1714 AND biblio.biblionumber = items.biblionumber
1715 AND biblio.biblionumber = biblioitems.biblionumber
1716 AND issues.borrowernumber = ?
1717 AND date_due < NOW()
1720 my $sth = C4::Context->dbh->prepare( $sql );
1721 $sth->execute( $borrowernumber );
1723 return $sth->fetchall_arrayref({});
1726 END { } # module clean-up code here (global destructor)