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 Date
::Calc qw
/Today Add_Delta_YM check_date Date_to_Days/;
28 use C4
::Log
; # logaction
34 use C4
::Members
::Attributes
qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
35 use C4
::NewsChannels
; #get slip news
39 use Koha
::Borrower
::Debarments
qw(IsDebarred);
40 use Text
::Unaccent
qw( unac_string );
41 use Koha
::AuthUtils
qw(hash_password);
44 use Module
::Load
::Conditional
qw( can_load );
45 if ( ! can_load
( modules
=> { 'Koha::NorwegianPatronDB' => undef } ) ) {
46 warn "Unable to load Koha::NorwegianPatronDB";
49 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
52 $VERSION = 3.07.00.049;
53 $debug = $ENV{DEBUG
} || 0;
65 &GetMemberIssuesAndFines
72 &GetFirstValidEmailAddress
73 &GetNoticeEmailAddress
84 &GetHideLostItemsPreference
87 &GetMemberAccountRecords
88 &GetBorNotifyAcctRecord
92 GetBorrowerCategorycode
93 &GetBorrowercategoryList
95 &GetBorrowersToExpunge
96 &GetBorrowersWhoHaveNeverBorrowed
97 &GetBorrowersWithIssuesHistoryOlderThan
100 &GetUpcomingMembershipExpires
108 GetBorrowersWithEmail
131 &ExtendMemberSubscriptionTo
147 C4::Members - Perl Module containing convenience functions for member handling
155 This module contains routines for adding, modifying and deleting members/patrons/borrowers
159 =head2 GetMemberDetails
161 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
163 Looks up a patron and returns information about him or her. If
164 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
165 up the borrower by number; otherwise, it looks up the borrower by card
168 C<$borrower> is a reference-to-hash whose keys are the fields of the
169 borrowers table in the Koha database. In addition,
170 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
171 about the patron. Its keys act as flags :
173 if $borrower->{flags}->{LOST} {
174 # Patron's card was reported lost
177 If the state of a flag means that the patron should not be
178 allowed to borrow any more books, then it will have a C<noissues> key
181 See patronflags for more details.
183 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
184 about the top-level permissions flags set for the borrower. For example,
185 if a user has the "editcatalogue" permission,
186 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
191 sub GetMemberDetails
{
192 my ( $borrowernumber, $cardnumber ) = @_;
193 my $dbh = C4
::Context
->dbh;
196 if ($borrowernumber) {
197 $sth = $dbh->prepare("
200 categories.description,
201 categories.BlockExpiredPatronOpacActions,
205 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
206 WHERE borrowernumber = ?
208 $sth->execute($borrowernumber);
210 elsif ($cardnumber) {
211 $sth = $dbh->prepare("
214 categories.description,
215 categories.BlockExpiredPatronOpacActions,
219 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
222 $sth->execute($cardnumber);
227 my $borrower = $sth->fetchrow_hashref;
228 return unless $borrower;
229 my ($amount) = GetMemberAccountRecords
($borrower->{borrowernumber
});
230 $borrower->{'amountoutstanding'} = $amount;
231 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
232 my $flags = patronflags
( $borrower);
235 $sth = $dbh->prepare("select bit,flag from userflags");
237 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
238 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
239 $accessflagshash->{$flag} = 1;
242 $borrower->{'flags'} = $flags;
243 $borrower->{'authflags'} = $accessflagshash;
245 # For the purposes of making templates easier, we'll define a
246 # 'showname' which is the alternate form the user's first name if
247 # 'other name' is defined.
248 if ($borrower->{category_type
} eq 'I') {
249 $borrower->{'showname'} = $borrower->{'othernames'};
250 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
252 $borrower->{'showname'} = $borrower->{'firstname'};
255 # Handle setting the true behavior for BlockExpiredPatronOpacActions
256 $borrower->{'BlockExpiredPatronOpacActions'} =
257 C4
::Context
->preference('BlockExpiredPatronOpacActions')
258 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
260 $borrower->{'is_expired'} = 0;
261 $borrower->{'is_expired'} = 1 if
262 defined($borrower->{dateexpiry
}) &&
263 $borrower->{'dateexpiry'} ne '0000-00-00' &&
264 Date_to_Days
( Today
() ) >
265 Date_to_Days
( split /-/, $borrower->{'dateexpiry'} );
267 return ($borrower); #, $flags, $accessflagshash);
272 $flags = &patronflags($patron);
274 This function is not exported.
276 The following will be set where applicable:
277 $flags->{CHARGES}->{amount} Amount of debt
278 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
279 $flags->{CHARGES}->{message} Message -- deprecated
281 $flags->{CREDITS}->{amount} Amount of credit
282 $flags->{CREDITS}->{message} Message -- deprecated
284 $flags->{ GNA } Patron has no valid address
285 $flags->{ GNA }->{noissues} Set for each GNA
286 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
288 $flags->{ LOST } Patron's card reported lost
289 $flags->{ LOST }->{noissues} Set for each LOST
290 $flags->{ LOST }->{message} Message -- deprecated
292 $flags->{DBARRED} Set if patron debarred, no access
293 $flags->{DBARRED}->{noissues} Set for each DBARRED
294 $flags->{DBARRED}->{message} Message -- deprecated
297 $flags->{ NOTES }->{message} The note itself. NOT deprecated
299 $flags->{ ODUES } Set if patron has overdue books.
300 $flags->{ ODUES }->{message} "Yes" -- deprecated
301 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
302 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
304 $flags->{WAITING} Set if any of patron's reserves are available
305 $flags->{WAITING}->{message} Message -- deprecated
306 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
310 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
311 overdue items. Its elements are references-to-hash, each describing an
312 overdue item. The keys are selected fields from the issues, biblio,
313 biblioitems, and items tables of the Koha database.
315 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
316 the overdue items, one per line. Deprecated.
318 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
319 available items. Each element is a reference-to-hash whose keys are
320 fields from the reserves table of the Koha database.
324 All the "message" fields that include language generated in this function are deprecated,
325 because such strings belong properly in the display layer.
327 The "message" field that comes from the DB is OK.
331 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
332 # FIXME rename this function.
335 my ( $patroninformation) = @_;
336 my $dbh=C4
::Context
->dbh;
337 my ($balance, $owing) = GetMemberAccountBalance
( $patroninformation->{'borrowernumber'});
340 my $noissuescharge = C4
::Context
->preference("noissuescharge") || 5;
341 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
342 $flaginfo{'amount'} = sprintf "%.02f", $owing;
343 if ( $owing > $noissuescharge && !C4
::Context
->preference("AllowFineOverride") ) {
344 $flaginfo{'noissues'} = 1;
346 $flags{'CHARGES'} = \
%flaginfo;
348 elsif ( $balance < 0 ) {
350 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
351 $flaginfo{'amount'} = sprintf "%.02f", $balance;
352 $flags{'CREDITS'} = \
%flaginfo;
354 if ( $patroninformation->{'gonenoaddress'}
355 && $patroninformation->{'gonenoaddress'} == 1 )
358 $flaginfo{'message'} = 'Borrower has no valid address.';
359 $flaginfo{'noissues'} = 1;
360 $flags{'GNA'} = \
%flaginfo;
362 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
364 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
365 $flaginfo{'noissues'} = 1;
366 $flags{'LOST'} = \
%flaginfo;
368 if ( $patroninformation->{'debarred'} && check_date
( split( /-/, $patroninformation->{'debarred'} ) ) ) {
369 if ( Date_to_Days
(Date
::Calc
::Today
) < Date_to_Days
( split( /-/, $patroninformation->{'debarred'} ) ) ) {
371 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
372 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
373 $flaginfo{'noissues'} = 1;
374 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
375 $flags{'DBARRED'} = \
%flaginfo;
378 if ( $patroninformation->{'borrowernotes'}
379 && $patroninformation->{'borrowernotes'} )
382 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
383 $flags{'NOTES'} = \
%flaginfo;
385 my ( $odues, $itemsoverdue ) = C4
::Overdues
::checkoverdues
($patroninformation->{'borrowernumber'});
386 if ( $odues && $odues > 0 ) {
388 $flaginfo{'message'} = "Yes";
389 $flaginfo{'itemlist'} = $itemsoverdue;
390 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
393 $flaginfo{'itemlisttext'} .=
394 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
396 $flags{'ODUES'} = \
%flaginfo;
398 my @itemswaiting = C4
::Reserves
::GetReservesFromBorrowernumber
( $patroninformation->{'borrowernumber'},'W' );
399 my $nowaiting = scalar @itemswaiting;
400 if ( $nowaiting > 0 ) {
402 $flaginfo{'message'} = "Reserved items available";
403 $flaginfo{'itemlist'} = \
@itemswaiting;
404 $flags{'WAITING'} = \
%flaginfo;
412 $borrower = &GetMember(%information);
414 Retrieve the first patron record meeting on criteria listed in the
415 C<%information> hash, which should contain one or more
416 pairs of borrowers column names and values, e.g.,
418 $borrower = GetMember(borrowernumber => id);
420 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
421 the C<borrowers> table in the Koha database.
423 FIXME: GetMember() is used throughout the code as a lookup
424 on a unique key such as the borrowernumber, but this meaning is not
425 enforced in the routine itself.
431 my ( %information ) = @_;
432 if (exists $information{borrowernumber
} && !defined $information{borrowernumber
}) {
433 #passing mysql's kohaadmin?? Makes no sense as a query
436 my $dbh = C4
::Context
->dbh;
438 q{SELECT borrowers.*, categories.category_type, categories.description
440 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
443 for (keys %information ) {
451 if (defined $information{$_}) {
453 push @values, $information{$_};
456 $select .= "$_ IS NULL";
459 $debug && warn $select, " ",values %information;
460 my $sth = $dbh->prepare("$select");
461 $sth->execute(map{$information{$_}} keys %information);
462 my $data = $sth->fetchall_arrayref({});
463 #FIXME interface to this routine now allows generation of a result set
464 #so whole array should be returned but bowhere in the current code expects this
472 =head2 GetMemberRelatives
474 @borrowernumbers = GetMemberRelatives($borrowernumber);
476 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
480 sub GetMemberRelatives
{
481 my $borrowernumber = shift;
482 my $dbh = C4
::Context
->dbh;
486 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
487 my $sth = $dbh->prepare($query);
488 $sth->execute($borrowernumber);
489 my $data = $sth->fetchrow_arrayref();
490 push @glist, $data->[0] if $data->[0];
491 my $guarantor = $data->[0] ?
$data->[0] : undef;
494 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
495 $sth = $dbh->prepare($query);
496 $sth->execute($borrowernumber);
497 while ($data = $sth->fetchrow_arrayref()) {
498 push @glist, $data->[0];
501 # Getting sibling guarantees
503 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
504 $sth = $dbh->prepare($query);
505 $sth->execute($guarantor);
506 while ($data = $sth->fetchrow_arrayref()) {
507 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
514 =head2 IsMemberBlocked
516 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
518 Returns whether a patron is restricted or has overdue items that may result
519 in a block of circulation privileges.
521 C<$block_status> can have the following values:
523 1 if the patron is currently restricted, in which case
524 C<$count> is the expiration date (9999-12-31 for indefinite)
526 -1 if the patron has overdue items, in which case C<$count> is the number of them
528 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
530 Existing active restrictions are checked before current overdue items.
534 sub IsMemberBlocked
{
535 my $borrowernumber = shift;
536 my $dbh = C4
::Context
->dbh;
538 my $blockeddate = Koha
::Borrower
::Debarments
::IsDebarred
($borrowernumber);
540 return ( 1, $blockeddate ) if $blockeddate;
542 # if he have late issues
543 my $sth = $dbh->prepare(
544 "SELECT COUNT(*) as latedocs
546 WHERE borrowernumber = ?
547 AND date_due < now()"
549 $sth->execute($borrowernumber);
550 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
552 return ( -1, $latedocs ) if $latedocs > 0;
557 =head2 GetMemberIssuesAndFines
559 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
561 Returns aggregate data about items borrowed by the patron with the
562 given borrowernumber.
564 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
565 number of overdue items the patron currently has borrowed. C<$issue_count> is the
566 number of books the patron currently has borrowed. C<$total_fines> is
567 the total fine currently due by the borrower.
572 sub GetMemberIssuesAndFines
{
573 my ( $borrowernumber ) = @_;
574 my $dbh = C4
::Context
->dbh;
575 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
577 $debug and warn $query."\n";
578 my $sth = $dbh->prepare($query);
579 $sth->execute($borrowernumber);
580 my $issue_count = $sth->fetchrow_arrayref->[0];
582 $sth = $dbh->prepare(
583 "SELECT COUNT(*) FROM issues
584 WHERE borrowernumber = ?
585 AND date_due < now()"
587 $sth->execute($borrowernumber);
588 my $overdue_count = $sth->fetchrow_arrayref->[0];
590 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
591 $sth->execute($borrowernumber);
592 my $total_fines = $sth->fetchrow_arrayref->[0];
594 return ($overdue_count, $issue_count, $total_fines);
600 my @columns = C4::Member::columns();
602 Returns an array of borrowers' table columns on success,
603 and an empty array on failure.
609 # Pure ANSI SQL goodness.
610 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
612 # Get the database handle.
613 my $dbh = C4
::Context
->dbh;
615 # Run the SQL statement to load STH's readonly properties.
616 my $sth = $dbh->prepare($sql);
617 my $rv = $sth->execute();
619 # This only fails if the table doesn't exist.
620 # This will always be called AFTER an install or upgrade,
621 # so borrowers will exist!
623 if ($sth->{NUM_OF_FIELDS
}>0) {
624 @data = @
{$sth->{NAME
}};
635 my $success = ModMember(borrowernumber => $borrowernumber,
636 [ field => value ]... );
638 Modify borrower's data. All date fields should ALREADY be in ISO format.
641 true on success, or false on failure
647 # test to know if you must update or not the borrower password
648 if (exists $data{password
}) {
649 if ($data{password
} eq '****' or $data{password
} eq '') {
650 delete $data{password
};
652 if ( C4
::Context
->preference('NorwegianPatronDBEnable') && C4
::Context
->preference('NorwegianPatronDBEnable') == 1 ) {
653 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
654 Koha
::NorwegianPatronDB
::NLUpdateHashedPIN
( $data{'borrowernumber'}, $data{password
} );
656 $data{password
} = hash_password
($data{password
});
659 my $old_categorycode = GetBorrowerCategorycode
( $data{borrowernumber
} );
661 # get only the columns of a borrower
662 my $schema = Koha
::Database
->new()->schema;
663 my @columns = $schema->source('Borrower')->columns;
664 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ?
( $_ => $data{$_} ) : () } keys(%data) };
665 delete $new_borrower->{flags
};
667 $new_borrower->{dateofbirth
} ||= undef if exists $new_borrower->{dateofbirth
};
668 $new_borrower->{dateenrolled
} ||= undef if exists $new_borrower->{dateenrolled
};
669 $new_borrower->{dateexpiry
} ||= undef if exists $new_borrower->{dateexpiry
};
670 $new_borrower->{debarred
} ||= undef if exists $new_borrower->{debarred
};
671 my $rs = $schema->resultset('Borrower')->search({
672 borrowernumber
=> $new_borrower->{borrowernumber
},
674 my $execute_success = $rs->update($new_borrower);
675 if ($execute_success ne '0E0') { # only proceed if the update was a success
676 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
677 # so when we update information for an adult we should check for guarantees and update the relevant part
678 # of their records, ie addresses and phone numbers
679 my $borrowercategory= GetBorrowercategory
( $data{'category_type'} );
680 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
681 # is adult check guarantees;
682 UpdateGuarantees
(%data);
685 # If the patron changes to a category with enrollment fee, we add a fee
686 if ( $data{categorycode
} and $data{categorycode
} ne $old_categorycode ) {
687 if ( C4
::Context
->preference('FeeOnChangePatronCategory') ) {
688 AddEnrolmentFeeIfNeeded
( $data{categorycode
}, $data{borrowernumber
} );
692 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
693 # cronjob will use for syncing with NL
694 if ( C4
::Context
->preference('NorwegianPatronDBEnable') && C4
::Context
->preference('NorwegianPatronDBEnable') == 1 ) {
695 my $borrowersync = Koha
::Database
->new->schema->resultset('BorrowerSync')->find({
696 'synctype' => 'norwegianpatrondb',
697 'borrowernumber' => $data{'borrowernumber'}
699 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
700 # we can sync as changed. And the "new sync" will pick up all changes since
701 # the patron was created anyway.
702 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
703 $borrowersync->update( { 'syncstatus' => 'edited' } );
705 # Set the value of 'sync'
706 $borrowersync->update( { 'sync' => $data{'sync'} } );
707 # Try to do the live sync
708 Koha
::NorwegianPatronDB
::NLSync
({ 'borrowernumber' => $data{'borrowernumber'} });
711 logaction
("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4
::Context
->preference("BorrowersLog");
713 return $execute_success;
718 $borrowernumber = &AddMember(%borrower);
720 insert new borrower into table
722 (%borrower keys are database columns. Database columns could be
723 different in different versions. Please look into database for correct
726 Returns the borrowernumber upon success
728 Returns as undef upon any db error without further processing
735 my $dbh = C4
::Context
->dbh;
736 my $schema = Koha
::Database
->new()->schema;
738 # generate a proper login if none provided
739 $data{'userid'} = Generate_Userid
( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
740 if ( $data{'userid'} eq '' || !Check_Userid
( $data{'userid'} ) );
742 # add expiration date if it isn't already there
743 unless ( $data{'dateexpiry'} ) {
744 $data{'dateexpiry'} = GetExpiryDate
( $data{'categorycode'}, output_pref
( { dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' } ) );
747 # add enrollment date if it isn't already there
748 unless ( $data{'dateenrolled'} ) {
749 $data{'dateenrolled'} = output_pref
( { dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' } );
752 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
754 $patron_category->default_privacy() eq 'default' ?
1
755 : $patron_category->default_privacy() eq 'never' ?
2
756 : $patron_category->default_privacy() eq 'forever' ?
0
758 # Make a copy of the plain text password for later use
759 my $plain_text_password = $data{'password'};
761 # create a disabled account if no password provided
762 $data{'password'} = ($data{'password'})? hash_password
($data{'password'}) : '!';
764 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
765 $data{'dateofbirth'} = undef if( not $data{'dateofbirth'} );
766 $data{'debarred'} = undef if ( not $data{'debarred'} );
768 # get only the columns of Borrower
769 my @columns = $schema->source('Borrower')->columns;
770 my $new_member = { map { join(' ',@columns) =~ /$_/ ?
( $_ => $data{$_} ) : () } keys(%data) } ;
771 delete $new_member->{borrowernumber
};
773 my $rs = $schema->resultset('Borrower');
774 $data{borrowernumber
} = $rs->create($new_member)->id;
776 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
777 # cronjob will use for syncing with NL
778 if ( exists $data{'borrowernumber'} && C4
::Context
->preference('NorwegianPatronDBEnable') && C4
::Context
->preference('NorwegianPatronDBEnable') == 1 ) {
779 Koha
::Database
->new->schema->resultset('BorrowerSync')->create({
780 'borrowernumber' => $data{'borrowernumber'},
781 'synctype' => 'norwegianpatrondb',
783 'syncstatus' => 'new',
784 'hashed_pin' => Koha
::NorwegianPatronDB
::NLEncryptPIN
( $plain_text_password ),
788 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
789 logaction
("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4
::Context
->preference("BorrowersLog");
791 AddEnrolmentFeeIfNeeded
( $data{categorycode
}, $data{borrowernumber
} );
793 return $data{borrowernumber
};
798 my $uniqueness = Check_Userid($userid,$borrowernumber);
800 $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 != '').
802 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.
805 0 for not unique (i.e. this $userid already exists)
806 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
811 my ( $uid, $borrowernumber ) = @_;
813 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
815 return 0 if ( $uid eq C4
::Context
->config('user') );
817 my $rs = Koha
::Database
->new()->schema()->resultset('Borrower');
820 $params->{userid
} = $uid;
821 $params->{borrowernumber
} = { '!=' => $borrowernumber } if ($borrowernumber);
823 my $count = $rs->count( $params );
825 return $count ?
0 : 1;
828 =head2 Generate_Userid
830 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
832 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
834 $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.
837 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).
841 sub Generate_Userid
{
842 my ($borrowernumber, $firstname, $surname) = @_;
845 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
847 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
848 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
849 $newuid = lc(($firstname)?
"$firstname.$surname" : $surname);
850 $newuid = unac_string
('utf-8',$newuid);
851 $newuid .= $offset unless $offset == 0;
854 } while (!Check_Userid
($newuid,$borrowernumber));
860 my ( $uid, $member, $digest ) = @_;
861 my $dbh = C4
::Context
->dbh;
863 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
864 #Then we need to tell the user and have them create a new one.
868 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
869 $sth->execute( $uid, $member );
870 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
874 #Everything is good so we can update the information.
877 "update borrowers set userid=?, password=? where borrowernumber=?");
878 $sth->execute( $uid, $digest, $member );
882 logaction
("MEMBERS", "CHANGE PASS", $member, "") if C4
::Context
->preference("BorrowersLog");
888 =head2 fixup_cardnumber
890 Warning: The caller is responsible for locking the members table in write
891 mode, to avoid database corruption.
895 use vars
qw( @weightings );
896 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
898 sub fixup_cardnumber {
899 my ($cardnumber) = @_;
900 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
902 # Find out whether member numbers should be generated
903 # automatically. Should be either "1" or something else.
904 # Defaults to "0", which is interpreted as "no".
906 # if ($cardnumber !~ /\S/ && $autonumber_members) {
907 ($autonumber_members) or return $cardnumber;
908 my $checkdigit = C4::Context->preference('checkdigit');
909 my $dbh = C4::Context->dbh;
910 if ( $checkdigit and $checkdigit eq 'katipo' ) {
912 # if checkdigit is selected, calculate katipo-style cardnumber.
913 # otherwise, just use the max()
914 # purpose: generate checksum'd member numbers.
915 # We'll assume we just got the max value of digits 2-8 of member #'s
916 # from the database and our job is to increment that by one,
917 # determine the 1st and 9th digits and return the full string.
918 my $sth = $dbh->prepare(
919 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
922 my $data = $sth->fetchrow_hashref;
923 $cardnumber = $data->{new_num};
924 if ( !$cardnumber ) { # If DB has no values,
925 $cardnumber = 1000000; # start at 1000000
931 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
932 # read weightings, left to right, 1 char at a time
933 my $temp1 = $weightings[$i];
935 # sequence left to right, 1 char at a time
936 my $temp2 = substr( $cardnumber, $i, 1 );
938 # mult each char 1-7 by its corresponding weighting
939 $sum += $temp1 * $temp2;
942 my $rem = ( $sum % 11 );
943 $rem = 'X' if $rem == 10;
945 return "V$cardnumber$rem";
948 my $sth = $dbh->prepare(
949 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
952 my ($result) = $sth->fetchrow;
955 return $cardnumber; # just here as a fallback/reminder
960 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
961 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
962 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
964 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
965 with children) and looks up the borrowers who are guaranteed by that
966 borrower (i.e., the patron's children).
968 C<&GetGuarantees> returns two values: an integer giving the number of
969 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
970 of references to hash, which gives the actual results.
976 my ($borrowernumber) = @_;
977 my $dbh = C4::Context->dbh;
980 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
982 $sth->execute($borrowernumber);
985 my $data = $sth->fetchall_arrayref({});
986 return ( scalar(@$data), $data );
989 =head2 UpdateGuarantees
991 &UpdateGuarantees($parent_borrno);
994 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
995 with the modified information
1000 sub UpdateGuarantees {
1002 my $dbh = C4::Context->dbh;
1003 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1004 foreach my $guarantee (@$guarantees){
1005 my $guaquery = qq|UPDATE borrowers
1006 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1007 WHERE borrowernumber=?
1009 my $sth = $dbh->prepare($guaquery);
1010 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1013 =head2 GetPendingIssues
1015 my $issues = &GetPendingIssues(@borrowernumber);
1017 Looks up what the patron with the given borrowernumber has borrowed.
1019 C<&GetPendingIssues> returns a
1020 reference-to-array where each element is a reference-to-hash; the
1021 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1022 The keys include C<biblioitems> fields except marc and marcxml.
1027 sub GetPendingIssues {
1028 my @borrowernumbers = @_;
1030 unless (@borrowernumbers ) { # return a ref_to_array
1031 return \@borrowernumbers; # to not cause surprise to caller
1034 # Borrowers part of the query
1036 for (my $i = 0; $i < @borrowernumbers; $i++) {
1037 $bquery .= ' issues.borrowernumber = ?';
1038 if ($i < $#borrowernumbers ) {
1043 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1044 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1045 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1046 # FIXME: namespace collision: other collisions possible.
1047 # FIXME: most of this data isn't really being used by callers.
1054 biblioitems.itemtype,
1057 biblioitems.publicationyear,
1058 biblioitems.publishercode,
1059 biblioitems.volumedate,
1060 biblioitems.volumedesc,
1063 borrowers.firstname,
1065 borrowers.cardnumber,
1066 issues.timestamp AS timestamp,
1067 issues.renewals AS renewals,
1068 issues.borrowernumber AS borrowernumber,
1069 items.renewals AS totalrenewals
1071 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1072 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1073 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1074 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1077 ORDER BY issues.issuedate"
1080 my $sth = C4::Context->dbh->prepare($query);
1081 $sth->execute(@borrowernumbers);
1082 my $data = $sth->fetchall_arrayref({});
1083 my $today = dt_from_string;
1084 foreach (@{$data}) {
1085 if ($_->{issuedate}) {
1086 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1088 $_->{date_due_sql} = $_->{date_due};
1089 # FIXME no need to have this value
1090 $_->{date_due} or next;
1091 $_->{date_due_sql} = $_->{date_due};
1092 # FIXME no need to have this value
1093 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1094 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1103 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1105 Looks up what the patron with the given borrowernumber has borrowed,
1106 and sorts the results.
1108 C<$sortkey> is the name of a field on which to sort the results. This
1109 should be the name of a field in the C<issues>, C<biblio>,
1110 C<biblioitems>, or C<items> table in the Koha database.
1112 C<$limit> is the maximum number of results to return.
1114 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1115 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1116 C<items> tables of the Koha database.
1122 my ( $borrowernumber, $order, $limit ) = @_;
1124 return unless $borrowernumber;
1125 $order = 'date_due desc' unless $order;
1127 my $dbh = C4::Context->dbh;
1129 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1131 LEFT JOIN items on items.itemnumber=issues.itemnumber
1132 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1133 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1134 WHERE borrowernumber=?
1136 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1138 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1139 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1140 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1141 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1142 order by ' . $order;
1144 $query .= " limit $limit";
1147 my $sth = $dbh->prepare($query);
1148 $sth->execute( $borrowernumber, $borrowernumber );
1149 return $sth->fetchall_arrayref( {} );
1153 =head2 GetMemberAccountRecords
1155 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1157 Looks up accounting data for the patron with the given borrowernumber.
1159 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1160 reference-to-array, where each element is a reference-to-hash; the
1161 keys are the fields of the C<accountlines> table in the Koha database.
1162 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1163 total amount outstanding for all of the account lines.
1167 sub GetMemberAccountRecords {
1168 my ($borrowernumber) = @_;
1169 my $dbh = C4::Context->dbh;
1175 WHERE borrowernumber=?);
1176 $strsth.=" ORDER BY accountlines_id desc";
1177 my $sth= $dbh->prepare( $strsth );
1178 $sth->execute( $borrowernumber );
1181 while ( my $data = $sth->fetchrow_hashref ) {
1182 if ( $data->{itemnumber} ) {
1183 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1184 $data->{biblionumber} = $biblio->{biblionumber};
1185 $data->{title} = $biblio->{title};
1187 $acctlines[$numlines] = $data;
1189 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1192 return ( $total, \@acctlines,$numlines);
1195 =head2 GetMemberAccountBalance
1197 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1199 Calculates amount immediately owing by the patron - non-issue charges.
1200 Based on GetMemberAccountRecords.
1201 Charges exempt from non-issue are:
1203 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1204 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1208 sub GetMemberAccountBalance {
1209 my ($borrowernumber) = @_;
1211 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1214 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1215 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1216 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1217 my $dbh = C4::Context->dbh;
1218 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1219 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1221 my %not_fine = map {$_ => 1} @not_fines;
1223 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1224 my $other_charges = 0;
1225 foreach (@$acctlines) {
1226 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1229 return ( $total, $total - $other_charges, $other_charges);
1232 =head2 GetBorNotifyAcctRecord
1234 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1236 Looks up accounting data for the patron with the given borrowernumber per file number.
1238 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1239 reference-to-array, where each element is a reference-to-hash; the
1240 keys are the fields of the C<accountlines> table in the Koha database.
1241 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1242 total amount outstanding for all of the account lines.
1246 sub GetBorNotifyAcctRecord {
1247 my ( $borrowernumber, $notifyid ) = @_;
1248 my $dbh = C4::Context->dbh;
1251 my $sth = $dbh->prepare(
1254 WHERE borrowernumber=?
1256 AND amountoutstanding != '0'
1257 ORDER BY notify_id,accounttype
1260 $sth->execute( $borrowernumber, $notifyid );
1262 while ( my $data = $sth->fetchrow_hashref ) {
1263 if ( $data->{itemnumber} ) {
1264 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1265 $data->{biblionumber} = $biblio->{biblionumber};
1266 $data->{title} = $biblio->{title};
1268 $acctlines[$numlines] = $data;
1270 $total += int(100 * $data->{'amountoutstanding'});
1273 return ( $total, \@acctlines, $numlines );
1276 =head2 checkuniquemember (OUEST-PROVENCE)
1278 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1280 Checks that a member exists or not in the database.
1282 C<&result> is nonzero (=exist) or 0 (=does not exist)
1283 C<&categorycode> is from categorycode table
1284 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1285 C<&surname> is the surname
1286 C<&firstname> is the firstname (only if collectivity=0)
1287 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1291 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1292 # This is especially true since first name is not even a required field.
1294 sub checkuniquemember {
1295 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1296 my $dbh = C4::Context->dbh;
1297 my $request = ($collectivity) ?
1298 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1300 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1301 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1302 my $sth = $dbh->prepare($request);
1303 if ($collectivity) {
1304 $sth->execute( uc($surname) );
1305 } elsif($dateofbirth){
1306 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1308 $sth->execute( uc($surname), ucfirst($firstname));
1310 my @data = $sth->fetchrow;
1311 ( $data[0] ) and return $data[0], $data[1];
1315 sub checkcardnumber {
1316 my ( $cardnumber, $borrowernumber ) = @_;
1318 # If cardnumber is null, we assume they're allowed.
1319 return 0 unless defined $cardnumber;
1321 my $dbh = C4::Context->dbh;
1322 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1323 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1324 my $sth = $dbh->prepare($query);
1327 ( $borrowernumber ? $borrowernumber : () )
1330 return 1 if $sth->fetchrow_hashref;
1332 my ( $min_length, $max_length ) = get_cardnumber_length();
1334 if length $cardnumber > $max_length
1335 or length $cardnumber < $min_length;
1340 =head2 get_cardnumber_length
1342 my ($min, $max) = C4::Members::get_cardnumber_length()
1344 Returns the minimum and maximum length for patron cardnumbers as
1345 determined by the CardnumberLength system preference, the
1346 BorrowerMandatoryField system preference, and the width of the
1351 sub get_cardnumber_length {
1352 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1353 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1354 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1355 # Is integer and length match
1356 if ( $cardnumber_length =~ m|^\d+$| ) {
1357 $min = $max = $cardnumber_length
1358 if $cardnumber_length >= $min
1359 and $cardnumber_length <= $max;
1361 # Else assuming it is a range
1362 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1363 $min = $1 if $1 and $min < $1;
1364 $max = $2 if $2 and $max > $2;
1368 return ( $min, $max );
1371 =head2 getzipnamecity (OUEST-PROVENCE)
1373 take all info from table city for the fields city and zip
1374 check for the name and the zip code of the city selected
1378 sub getzipnamecity {
1380 my $dbh = C4::Context->dbh;
1383 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1384 $sth->execute($cityid);
1385 my @data = $sth->fetchrow;
1386 return $data[0], $data[1], $data[2], $data[3];
1390 =head2 getdcity (OUEST-PROVENCE)
1392 recover cityid with city_name condition
1397 my ($city_name) = @_;
1398 my $dbh = C4::Context->dbh;
1399 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1400 $sth->execute($city_name);
1401 my $data = $sth->fetchrow;
1405 =head2 GetFirstValidEmailAddress
1407 $email = GetFirstValidEmailAddress($borrowernumber);
1409 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1410 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1415 sub GetFirstValidEmailAddress {
1416 my $borrowernumber = shift;
1417 my $dbh = C4::Context->dbh;
1418 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1419 $sth->execute( $borrowernumber );
1420 my $data = $sth->fetchrow_hashref;
1422 if ($data->{'email'}) {
1423 return $data->{'email'};
1424 } elsif ($data->{'emailpro'}) {
1425 return $data->{'emailpro'};
1426 } elsif ($data->{'B_email'}) {
1427 return $data->{'B_email'};
1433 =head2 GetNoticeEmailAddress
1435 $email = GetNoticeEmailAddress($borrowernumber);
1437 Return the email address of borrower used for notices, given the borrowernumber.
1438 Returns the empty string if no email address.
1442 sub GetNoticeEmailAddress {
1443 my $borrowernumber = shift;
1445 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1446 # if syspref is set to 'first valid' (value == OFF), look up email address
1447 if ( $which_address eq 'OFF' ) {
1448 return GetFirstValidEmailAddress($borrowernumber);
1450 # specified email address field
1451 my $dbh = C4::Context->dbh;
1452 my $sth = $dbh->prepare( qq{
1453 SELECT $which_address AS primaryemail
1455 WHERE borrowernumber=?
1457 $sth->execute($borrowernumber);
1458 my $data = $sth->fetchrow_hashref;
1459 return $data->{'primaryemail'} || '';
1462 =head2 GetExpiryDate
1464 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1466 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1467 Return date is also in ISO format.
1472 my ( $categorycode, $dateenrolled ) = @_;
1474 if ($categorycode) {
1475 my $dbh = C4::Context->dbh;
1476 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1477 $sth->execute($categorycode);
1478 $enrolments = $sth->fetchrow_hashref;
1480 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1481 my @date = split (/-/,$dateenrolled);
1482 if($enrolments->{enrolmentperiod}){
1483 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1485 return $enrolments->{enrolmentperioddate};
1489 =head2 GetUpcomingMembershipExpires
1491 my $upcoming_mem_expires = GetUpcomingMembershipExpires();
1495 sub GetUpcomingMembershipExpires {
1496 my $dbh = C4::Context->dbh;
1497 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1498 my $dateexpiry = output_pref({ dt => (dt_from_string()->add( days => $days)), dateformat => 'iso', dateonly => 1 });
1501 SELECT borrowers.*, categories.description,
1502 branches.branchname, branches.branchemail FROM borrowers
1503 LEFT JOIN branches on borrowers.branchcode = branches.branchcode
1504 LEFT JOIN categories on borrowers.categorycode = categories.categorycode
1505 WHERE dateexpiry = ?;
1507 my $sth = $dbh->prepare($query);
1508 $sth->execute($dateexpiry);
1509 my $results = $sth->fetchall_arrayref({});
1513 =head2 GetborCatFromCatType
1515 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1517 Looks up the different types of borrowers in the database. Returns two
1518 elements: a reference-to-array, which lists the borrower category
1519 codes, and a reference-to-hash, which maps the borrower category codes
1520 to category descriptions.
1525 sub GetborCatFromCatType {
1526 my ( $category_type, $action, $no_branch_limit ) = @_;
1528 my $branch_limit = $no_branch_limit
1530 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1532 # FIXME - This API seems both limited and dangerous.
1533 my $dbh = C4::Context->dbh;
1536 SELECT categories.categorycode, categories.description
1540 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1543 $request .= " $action ";
1544 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1546 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1548 $request .= " ORDER BY categorycode";
1550 my $sth = $dbh->prepare($request);
1552 $action ? $category_type : (),
1553 $branch_limit ? $branch_limit : ()
1559 while ( my $data = $sth->fetchrow_hashref ) {
1560 push @codes, $data->{'categorycode'};
1561 $labels{ $data->{'categorycode'} } = $data->{'description'};
1564 return ( \@codes, \%labels );
1567 =head2 GetBorrowercategory
1569 $hashref = &GetBorrowercategory($categorycode);
1571 Given the borrower's category code, the function returns the corresponding
1572 data hashref for a comprehensive information display.
1576 sub GetBorrowercategory {
1578 my $dbh = C4::Context->dbh;
1582 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1584 WHERE categorycode = ?"
1586 $sth->execute($catcode);
1588 $sth->fetchrow_hashref;
1592 } # sub getborrowercategory
1595 =head2 GetBorrowerCategorycode
1597 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1599 Given the borrowernumber, the function returns the corresponding categorycode
1603 sub GetBorrowerCategorycode {
1604 my ( $borrowernumber ) = @_;
1605 my $dbh = C4::Context->dbh;
1606 my $sth = $dbh->prepare( qq{
1609 WHERE borrowernumber = ?
1611 $sth->execute( $borrowernumber );
1612 return $sth->fetchrow;
1615 =head2 GetBorrowercategoryList
1617 $arrayref_hashref = &GetBorrowercategoryList;
1618 If no category code provided, the function returns all the categories.
1622 sub GetBorrowercategoryList {
1623 my $no_branch_limit = @_ ? shift : 0;
1624 my $branch_limit = $no_branch_limit
1626 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1627 my $dbh = C4::Context->dbh;
1628 my $query = "SELECT categories.* FROM categories";
1630 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1631 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1633 $query .= " ORDER BY description";
1634 my $sth = $dbh->prepare( $query );
1635 $sth->execute( $branch_limit ? $branch_limit : () );
1636 my $data = $sth->fetchall_arrayref( {} );
1639 } # sub getborrowercategory
1643 $dateofbirth,$date = &GetAge($date);
1645 this function return the borrowers age with the value of dateofbirth
1651 my ( $date, $date_ref ) = @_;
1653 if ( not defined $date_ref ) {
1654 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1657 my ( $year1, $month1, $day1 ) = split /-/, $date;
1658 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1660 my $age = $year2 - $year1;
1661 if ( $month1 . $day1 > $month2 . $day2 ) {
1670 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1671 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1672 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1674 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1675 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1677 This function sets the borrower's dateofbirth to match the given age.
1678 Optionally relative to the given $datetime_reference.
1680 @PARAM1 koha.borrowers-object
1681 @PARAM2 DateTime::Duration-object as the desired age
1682 OR a ISO 8601 Date. (To make the API more pleasant)
1683 @PARAM3 DateTime-object as the relative date, defaults to now().
1684 RETURNS The given borrower reference @PARAM1.
1685 DIES If there was an error with the ISO Date handling.
1691 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1692 $datetime_ref = DateTime->now() unless $datetime_ref;
1694 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1695 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1696 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1699 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1703 my $new_datetime_ref = $datetime_ref->clone();
1704 $new_datetime_ref->subtract_duration( $datetimeduration );
1706 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1713 $cityarrayref = GetCities();
1715 Returns an array_ref of the entries in the cities table
1716 If there are entries in the table an empty row is returned
1717 This is currently only used to populate a popup in memberentry
1723 my $dbh = C4::Context->dbh;
1724 my $city_arr = $dbh->selectall_arrayref(
1725 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1727 if ( @{$city_arr} ) {
1728 unshift @{$city_arr}, {
1729 city_zipcode => q{},
1733 city_country
=> q{},
1740 =head2 GetSortDetails (OUEST-PROVENCE)
1742 ($lib) = &GetSortDetails($category,$sortvalue);
1744 Returns the authorized value details
1745 C<&$lib>return value of authorized value details
1746 C<&$sortvalue>this is the value of authorized value
1747 C<&$category>this is the value of authorized value category
1751 sub GetSortDetails
{
1752 my ( $category, $sortvalue ) = @_;
1753 my $dbh = C4
::Context
->dbh;
1754 my $query = qq|SELECT lib
1755 FROM authorised_values
1757 AND authorised_value
=?
|;
1758 my $sth = $dbh->prepare($query);
1759 $sth->execute( $category, $sortvalue );
1760 my $lib = $sth->fetchrow;
1761 return ($lib) if ($lib);
1762 return ($sortvalue) unless ($lib);
1765 =head2 MoveMemberToDeleted
1767 $result = &MoveMemberToDeleted($borrowernumber);
1769 Copy the record from borrowers to deletedborrowers table.
1770 The routine returns 1 for success, undef for failure.
1774 sub MoveMemberToDeleted
{
1775 my ($member) = shift or return;
1777 my $schema = Koha
::Database
->new()->schema();
1778 my $borrowers_rs = $schema->resultset('Borrower');
1779 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1780 my $borrower = $borrowers_rs->find($member);
1781 return unless $borrower;
1783 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1785 return $deleted ?
1 : undef;
1790 DelMember($borrowernumber);
1792 This function remove directly a borrower whitout writing it on deleteborrower.
1793 + Deletes reserves for the borrower
1798 my $dbh = C4
::Context
->dbh;
1799 my $borrowernumber = shift;
1800 #warn "in delmember with $borrowernumber";
1801 return unless $borrowernumber; # borrowernumber is mandatory.
1803 my $query = qq|DELETE
1805 WHERE borrowernumber
=?
|;
1806 my $sth = $dbh->prepare($query);
1807 $sth->execute($borrowernumber);
1811 WHERE borrowernumber = ?
1813 $sth = $dbh->prepare($query);
1814 $sth->execute($borrowernumber);
1815 logaction
("MEMBERS", "DELETE", $borrowernumber, "") if C4
::Context
->preference("BorrowersLog");
1819 =head2 HandleDelBorrower
1821 HandleDelBorrower($borrower);
1823 When a member is deleted (DelMember in Members.pm), you should call me first.
1824 This routine deletes/moves lists and entries for the deleted member/borrower.
1825 Lists owned by the borrower are deleted, but entries from the borrower to
1826 other lists are kept.
1830 sub HandleDelBorrower
{
1833 my $dbh = C4
::Context
->dbh;
1835 #Delete all lists and all shares of this borrower
1836 #Consistent with the approach Koha uses on deleting individual lists
1837 #Note that entries in virtualshelfcontents added by this borrower to
1838 #lists of others will be handled by a table constraint: the borrower
1839 #is set to NULL in those entries.
1840 $query="DELETE FROM virtualshelves WHERE owner=?";
1841 $dbh->do($query,undef,($borrower));
1844 #We could handle the above deletes via a constraint too.
1845 #But a new BZ report 11889 has been opened to discuss another approach.
1846 #Instead of deleting we could also disown lists (based on a pref).
1847 #In that way we could save shared and public lists.
1848 #The current table constraints support that idea now.
1849 #This pref should then govern the results of other routines/methods such as
1850 #Koha::Virtualshelf->new->delete too.
1853 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1855 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1857 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1862 sub ExtendMemberSubscriptionTo
{
1863 my ( $borrowerid,$date) = @_;
1864 my $dbh = C4
::Context
->dbh;
1865 my $borrower = GetMember
('borrowernumber'=>$borrowerid);
1867 $date = (C4
::Context
->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1868 eval { output_pref
( { dt
=> dt_from_string
( $borrower->{'dateexpiry'} ), dateonly
=> 1, dateformat
=> 'iso' } ); }
1870 output_pref
( { dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' } );
1871 $date = GetExpiryDate
( $borrower->{'categorycode'}, $date );
1873 my $sth = $dbh->do(<<EOF);
1875 SET dateexpiry='$date'
1876 WHERE borrowernumber='$borrowerid'
1879 AddEnrolmentFeeIfNeeded
( $borrower->{categorycode
}, $borrower->{borrowernumber
} );
1881 logaction
("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4
::Context
->preference("BorrowersLog");
1882 return $date if ($sth);
1886 =head2 GetTitles (OUEST-PROVENCE)
1888 ($borrowertitle)= &GetTitles();
1890 Looks up the different title . Returns array with all borrowers title
1895 my @borrowerTitle = split (/,|\|/,C4
::Context
->preference('BorrowersTitles'));
1896 unshift( @borrowerTitle, "" );
1897 my $count=@borrowerTitle;
1902 return ( \
@borrowerTitle);
1906 =head2 GetPatronImage
1908 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1910 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1914 sub GetPatronImage
{
1915 my ($borrowernumber) = @_;
1916 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1917 my $dbh = C4
::Context
->dbh;
1918 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1919 my $sth = $dbh->prepare($query);
1920 $sth->execute($borrowernumber);
1921 my $imagedata = $sth->fetchrow_hashref;
1922 warn "Database error!" if $sth->errstr;
1923 return $imagedata, $sth->errstr;
1926 =head2 PutPatronImage
1928 PutPatronImage($cardnumber, $mimetype, $imgfile);
1930 Stores patron binary image data and mimetype in database.
1931 NOTE: This function is good for updating images as well as inserting new images in the database.
1935 sub PutPatronImage
{
1936 my ($cardnumber, $mimetype, $imgfile) = @_;
1937 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ?
"Imagefile" : "No Imagefile") if $debug;
1938 my $dbh = C4
::Context
->dbh;
1939 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1940 my $sth = $dbh->prepare($query);
1941 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1942 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1943 return $sth->errstr;
1946 =head2 RmPatronImage
1948 my ($dberror) = RmPatronImage($borrowernumber);
1950 Removes the image for the patron with the supplied borrowernumber.
1955 my ($borrowernumber) = @_;
1956 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1957 my $dbh = C4
::Context
->dbh;
1958 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1959 my $sth = $dbh->prepare($query);
1960 $sth->execute($borrowernumber);
1961 my $dberror = $sth->errstr;
1962 warn "Database error!" if $sth->errstr;
1966 =head2 GetHideLostItemsPreference
1968 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1970 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1971 C<&$hidelostitemspref>return value of function, 0 or 1
1975 sub GetHideLostItemsPreference
{
1976 my ($borrowernumber) = @_;
1977 my $dbh = C4
::Context
->dbh;
1978 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1979 my $sth = $dbh->prepare($query);
1980 $sth->execute($borrowernumber);
1981 my $hidelostitems = $sth->fetchrow;
1982 return $hidelostitems;
1985 =head2 GetBorrowersToExpunge
1987 $borrowers = &GetBorrowersToExpunge(
1988 not_borrowered_since => $not_borrowered_since,
1989 expired_before => $expired_before,
1990 category_code => $category_code,
1991 branchcode => $branchcode
1994 This function get all borrowers based on the given criteria.
1998 sub GetBorrowersToExpunge
{
2001 my $filterdate = $params->{'not_borrowered_since'};
2002 my $filterexpiry = $params->{'expired_before'};
2003 my $filtercategory = $params->{'category_code'};
2004 my $filterbranch = $params->{'branchcode'} ||
2005 ((C4
::Context
->preference('IndependentBranches')
2006 && C4
::Context
->userenv
2007 && !C4
::Context
->IsSuperLibrarian()
2008 && C4
::Context
->userenv->{branch
})
2009 ? C4
::Context
->userenv->{branch
}
2012 my $dbh = C4
::Context
->dbh;
2014 SELECT borrowers
.borrowernumber
,
2015 MAX
(old_issues
.timestamp
) AS latestissue
,
2016 MAX
(issues
.timestamp
) AS currentissue
2018 JOIN categories USING
(categorycode
)
2022 WHERE guarantorid IS NOT NULL
2023 AND guarantorid
<> 0
2024 ) as tmp ON borrowers
.borrowernumber
=tmp
.guarantorid
2025 LEFT JOIN old_issues USING
(borrowernumber
)
2026 LEFT JOIN issues USING
(borrowernumber
)
2027 WHERE category_type
<> 'S'
2028 AND tmp
.guarantorid IS NULL
2032 if ( $filterbranch && $filterbranch ne "" ) {
2033 $query.= " AND borrowers.branchcode = ? ";
2034 push( @query_params, $filterbranch );
2036 if ( $filterexpiry ) {
2037 $query .= " AND dateexpiry < ? ";
2038 push( @query_params, $filterexpiry );
2040 if ( $filtercategory ) {
2041 $query .= " AND categorycode = ? ";
2042 push( @query_params, $filtercategory );
2044 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2045 if ( $filterdate ) {
2046 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2047 push @query_params,$filterdate;
2049 warn $query if $debug;
2051 my $sth = $dbh->prepare($query);
2052 if (scalar(@query_params)>0){
2053 $sth->execute(@query_params);
2060 while ( my $data = $sth->fetchrow_hashref ) {
2061 push @results, $data;
2066 =head2 GetBorrowersWhoHaveNeverBorrowed
2068 $results = &GetBorrowersWhoHaveNeverBorrowed
2070 This function get all borrowers who have never borrowed.
2072 I<$result> is a ref to an array which all elements are a hasref.
2076 sub GetBorrowersWhoHaveNeverBorrowed
{
2077 my $filterbranch = shift ||
2078 ((C4
::Context
->preference('IndependentBranches')
2079 && C4
::Context
->userenv
2080 && !C4
::Context
->IsSuperLibrarian()
2081 && C4
::Context
->userenv->{branch
})
2082 ? C4
::Context
->userenv->{branch
}
2084 my $dbh = C4
::Context
->dbh;
2086 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2088 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2089 WHERE issues.borrowernumber IS NULL
2092 if ($filterbranch && $filterbranch ne ""){
2093 $query.=" AND borrowers.branchcode= ?";
2094 push @query_params,$filterbranch;
2096 warn $query if $debug;
2098 my $sth = $dbh->prepare($query);
2099 if (scalar(@query_params)>0){
2100 $sth->execute(@query_params);
2107 while ( my $data = $sth->fetchrow_hashref ) {
2108 push @results, $data;
2113 =head2 GetBorrowersWithIssuesHistoryOlderThan
2115 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2117 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2119 I<$result> is a ref to an array which all elements are a hashref.
2120 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2124 sub GetBorrowersWithIssuesHistoryOlderThan
{
2125 my $dbh = C4
::Context
->dbh;
2126 my $date = shift ||POSIX
::strftime
("%Y-%m-%d",localtime());
2127 my $filterbranch = shift ||
2128 ((C4
::Context
->preference('IndependentBranches')
2129 && C4
::Context
->userenv
2130 && !C4
::Context
->IsSuperLibrarian()
2131 && C4
::Context
->userenv->{branch
})
2132 ? C4
::Context
->userenv->{branch
}
2135 SELECT count(borrowernumber) as n,borrowernumber
2137 WHERE returndate < ?
2138 AND borrowernumber IS NOT NULL
2141 push @query_params, $date;
2143 $query.=" AND branchcode = ?";
2144 push @query_params, $filterbranch;
2146 $query.=" GROUP BY borrowernumber ";
2147 warn $query if $debug;
2148 my $sth = $dbh->prepare($query);
2149 $sth->execute(@query_params);
2152 while ( my $data = $sth->fetchrow_hashref ) {
2153 push @results, $data;
2158 =head2 GetBorrowersNamesAndLatestIssue
2160 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2162 this function get borrowers Names and surnames and Issue information.
2164 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2165 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2169 sub GetBorrowersNamesAndLatestIssue
{
2170 my $dbh = C4
::Context
->dbh;
2171 my @borrowernumbers=@_;
2173 SELECT surname,lastname, phone, email,max(timestamp)
2175 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2176 GROUP BY borrowernumber
2178 my $sth = $dbh->prepare($query);
2180 my $results = $sth->fetchall_arrayref({});
2186 my $success = ModPrivacy( $borrowernumber, $privacy );
2188 Update the privacy of a patron.
2191 true on success, false on failure
2196 my $borrowernumber = shift;
2197 my $privacy = shift;
2198 return unless defined $borrowernumber;
2199 return unless $borrowernumber =~ /^\d+$/;
2201 return ModMember
( borrowernumber
=> $borrowernumber,
2202 privacy
=> $privacy );
2207 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2209 Adds a message to the messages table for the given borrower.
2218 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2220 my $dbh = C4
::Context
->dbh;
2222 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2226 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2227 my $sth = $dbh->prepare($query);
2228 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2229 logaction
("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4
::Context
->preference("BorrowersLog");
2235 GetMessages( $borrowernumber, $type );
2237 $type is message type, B for borrower, or L for Librarian.
2238 Empty type returns all messages of any type.
2240 Returns all messages for the given borrowernumber
2245 my ( $borrowernumber, $type, $branchcode ) = @_;
2251 my $dbh = C4
::Context
->dbh;
2254 branches.branchname,
2257 messages.branchcode LIKE '$branchcode' AS can_delete
2258 FROM messages, branches
2259 WHERE borrowernumber = ?
2260 AND message_type LIKE ?
2261 AND messages.branchcode = branches.branchcode
2262 ORDER BY message_date DESC";
2263 my $sth = $dbh->prepare($query);
2264 $sth->execute( $borrowernumber, $type ) ;
2267 while ( my $data = $sth->fetchrow_hashref ) {
2268 $data->{message_date_formatted
} = output_pref
( { dt
=> dt_from_string
( $data->{message_date
} ), dateonly
=> 1, dateformat
=> 'iso' } );
2269 push @results, $data;
2277 GetMessagesCount( $borrowernumber, $type );
2279 $type is message type, B for borrower, or L for Librarian.
2280 Empty type returns all messages of any type.
2282 Returns the number of messages for the given borrowernumber
2286 sub GetMessagesCount
{
2287 my ( $borrowernumber, $type, $branchcode ) = @_;
2293 my $dbh = C4
::Context
->dbh;
2295 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2296 my $sth = $dbh->prepare($query);
2297 $sth->execute( $borrowernumber, $type ) ;
2300 my $data = $sth->fetchrow_hashref;
2301 my $count = $data->{'MsgCount'};
2308 =head2 DeleteMessage
2310 DeleteMessage( $message_id );
2315 my ( $message_id ) = @_;
2317 my $dbh = C4
::Context
->dbh;
2318 my $query = "SELECT * FROM messages WHERE message_id = ?";
2319 my $sth = $dbh->prepare($query);
2320 $sth->execute( $message_id );
2321 my $message = $sth->fetchrow_hashref();
2323 $query = "DELETE FROM messages WHERE message_id = ?";
2324 $sth = $dbh->prepare($query);
2325 $sth->execute( $message_id );
2326 logaction
("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4
::Context
->preference("BorrowersLog");
2331 IssueSlip($branchcode, $borrowernumber, $quickslip)
2333 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2335 $quickslip is boolean, to indicate whether we want a quick slip
2337 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2373 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2378 my ($branch, $borrowernumber, $quickslip) = @_;
2380 # FIXME Check callers before removing this statement
2381 #return unless $borrowernumber;
2383 my @issues = @
{ GetPendingIssues
($borrowernumber) };
2385 for my $issue (@issues) {
2386 $issue->{date_due
} = $issue->{date_due_sql
};
2388 my $today = output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
2389 if ( substr( $issue->{issuedate
}, 0, 10 ) eq $today
2390 or substr( $issue->{lastreneweddate
}, 0, 10 ) eq $today ) {
2396 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2398 my $s = $b->{timestamp
} <=> $a->{timestamp
};
2400 $b->{issuedate
} <=> $a->{issuedate
} : $s;
2403 my ($letter_code, %repeat);
2405 $letter_code = 'ISSUEQSLIP';
2407 'checkedout' => [ map {
2410 'biblioitems' => $_,
2412 }, grep { $_->{'now'} } @issues ],
2416 $letter_code = 'ISSUESLIP';
2418 'checkedout' => [ map {
2421 'biblioitems' => $_,
2423 }, grep { !$_->{'overdue'} } @issues ],
2425 'overdue' => [ map {
2428 'biblioitems' => $_,
2430 }, grep { $_->{'overdue'} } @issues ],
2433 $_->{'timestamp'} = $_->{'newdate'};
2435 } @
{ GetNewsToDisplay
("slip",$branch) } ],
2439 return C4
::Letters
::GetPreparedLetter
(
2440 module
=> 'circulation',
2441 letter_code
=> $letter_code,
2442 branchcode
=> $branch,
2444 'branches' => $branch,
2445 'borrowers' => $borrowernumber,
2451 =head2 GetBorrowersWithEmail
2453 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2455 This gets a list of users and their basic details from their email address.
2456 As it's possible for multiple user to have the same email address, it provides
2457 you with all of them. If there is no userid for the user, there will be an
2458 C<undef> there. An empty list will be returned if there are no matches.
2462 sub GetBorrowersWithEmail
{
2465 my $dbh = C4
::Context
->dbh;
2467 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2468 my $sth=$dbh->prepare($query);
2469 $sth->execute($email);
2471 while (my $ref = $sth->fetch) {
2474 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2478 =head2 AddMember_Opac
2482 sub AddMember_Opac
{
2483 my ( %borrower ) = @_;
2485 $borrower{'categorycode'} = C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
2487 my $sr = new String
::Random
;
2488 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2489 my $password = $sr->randpattern("AAAAAAAAAA");
2490 $borrower{'password'} = $password;
2492 $borrower{'cardnumber'} = fixup_cardnumber
();
2494 my $borrowernumber = AddMember
(%borrower);
2496 return ( $borrowernumber, $password );
2499 =head2 AddEnrolmentFeeIfNeeded
2501 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2503 Add enrolment fee for a patron if needed.
2507 sub AddEnrolmentFeeIfNeeded
{
2508 my ( $categorycode, $borrowernumber ) = @_;
2509 # check for enrollment fee & add it if needed
2510 my $dbh = C4
::Context
->dbh;
2511 my $sth = $dbh->prepare(q{
2514 WHERE categorycode=?
2516 $sth->execute( $categorycode );
2518 warn sprintf('Database returned the following error: %s', $sth->errstr);
2521 my ($enrolmentfee) = $sth->fetchrow;
2522 if ($enrolmentfee && $enrolmentfee > 0) {
2523 # insert fee in patron debts
2524 C4
::Accounts
::manualinvoice
( $borrowernumber, '', '', 'A', $enrolmentfee );
2533 my ( $borrowernumber ) = @_;
2535 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2536 my $sth = C4
::Context
->dbh->prepare( $sql );
2537 $sth->execute( $borrowernumber );
2538 my ( $count ) = $sth->fetchrow_array();
2543 =head2 DeleteExpiredOpacRegistrations
2545 Delete accounts that haven't been upgraded from the 'temporary' category
2546 Returns the number of removed patrons
2550 sub DeleteExpiredOpacRegistrations
{
2552 my $delay = C4
::Context
->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2553 my $category_code = C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
2555 return 0 if not $category_code or not defined $delay or $delay eq q
||;
2558 SELECT borrowernumber
2560 WHERE categorycode
= ? AND DATEDIFF
( NOW
(), dateenrolled
) > ?
|;
2562 my $dbh = C4
::Context
->dbh;
2563 my $sth = $dbh->prepare($query);
2564 $sth->execute( $category_code, $delay );
2566 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2567 DelMember
($borrowernumber);
2573 =head2 DeleteUnverifiedOpacRegistrations
2575 Delete all unverified self registrations in borrower_modifications,
2576 older than the specified number of days.
2580 sub DeleteUnverifiedOpacRegistrations
{
2582 my $dbh = C4
::Context
->dbh;
2584 DELETE FROM borrower_modifications
2585 WHERE borrowernumber
= 0 AND DATEDIFF
( NOW
(), timestamp
) > ?
|;
2586 my $cnt=$dbh->do($sql, undef, ($days) );
2587 return $cnt eq '0E0'?
0: $cnt;
2590 sub GetOverduesForPatron
{
2591 my ( $borrowernumber ) = @_;
2595 FROM issues, items, biblio, biblioitems
2596 WHERE items.itemnumber=issues.itemnumber
2597 AND biblio.biblionumber = items.biblionumber
2598 AND biblio.biblionumber = biblioitems.biblionumber
2599 AND issues.borrowernumber = ?
2600 AND date_due < NOW()
2603 my $sth = C4
::Context
->dbh->prepare( $sql );
2604 $sth->execute( $borrowernumber );
2606 return $sth->fetchall_arrayref({});
2609 END { } # module clean-up code here (global destructor)