Bug 16281: Remove the use of 'onclick' from Reports module
[koha.git] / C4 / Members.pm
blobed82f86ca59ebc5ed744c4c149c3c70c322ab70f
1 package C4::Members;
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>.
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
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
29 use C4::Overdues;
30 use C4::Reserves;
31 use C4::Accounts;
32 use C4::Biblio;
33 use C4::Letters;
34 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
35 use C4::NewsChannels; #get slip news
36 use DateTime;
37 use Koha::Database;
38 use Koha::DateUtils;
39 use Koha::Patron::Debarments qw(IsDebarred);
40 use Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
42 use Koha::Database;
43 use Koha::List::Patron;
45 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
47 use Module::Load::Conditional qw( can_load );
48 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
49 $debug && warn "Unable to load Koha::NorwegianPatronDB";
53 BEGIN {
54 $debug = $ENV{DEBUG} || 0;
55 require Exporter;
56 @ISA = qw(Exporter);
57 #Get data
58 push @EXPORT, qw(
59 &Search
60 &GetMemberDetails
61 &GetMemberRelatives
62 &GetMember
64 &GetMemberIssuesAndFines
65 &GetPendingIssues
66 &GetAllIssues
68 &GetFirstValidEmailAddress
69 &GetNoticeEmailAddress
71 &GetAge
72 &GetSortDetails
73 &GetTitles
75 &GetHideLostItemsPreference
77 &IsMemberBlocked
78 &GetMemberAccountRecords
79 &GetBorNotifyAcctRecord
81 &GetborCatFromCatType
82 &GetBorrowercategory
83 GetBorrowerCategorycode
84 &GetBorrowercategoryList
86 &GetBorrowersToExpunge
87 &GetBorrowersWhoHaveNeverBorrowed
88 &GetBorrowersWithIssuesHistoryOlderThan
90 &GetExpiryDate
91 &GetUpcomingMembershipExpires
93 &IssueSlip
94 GetBorrowersWithEmail
96 HasOverdues
97 GetOverduesForPatron
100 #Modify data
101 push @EXPORT, qw(
102 &ModMember
103 &changepassword
106 #Delete data
107 push @EXPORT, qw(
108 &DelMember
111 #Insert data
112 push @EXPORT, qw(
113 &AddMember
114 &AddMember_Opac
115 &MoveMemberToDeleted
116 &ExtendMemberSubscriptionTo
119 #Check data
120 push @EXPORT, qw(
121 &checkuniquemember
122 &checkuserpassword
123 &Check_Userid
124 &Generate_Userid
125 &fixup_cardnumber
126 &checkcardnumber
130 =head1 NAME
132 C4::Members - Perl Module containing convenience functions for member handling
134 =head1 SYNOPSIS
136 use C4::Members;
138 =head1 DESCRIPTION
140 This module contains routines for adding, modifying and deleting members/patrons/borrowers
142 =head1 FUNCTIONS
144 =head2 GetMemberDetails
146 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
148 Looks up a patron and returns information about him or her. If
149 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
150 up the borrower by number; otherwise, it looks up the borrower by card
151 number.
153 C<$borrower> is a reference-to-hash whose keys are the fields of the
154 borrowers table in the Koha database. In addition,
155 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
156 about the patron. Its keys act as flags :
158 if $borrower->{flags}->{LOST} {
159 # Patron's card was reported lost
162 If the state of a flag means that the patron should not be
163 allowed to borrow any more books, then it will have a C<noissues> key
164 with a true value.
166 See patronflags for more details.
168 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
169 about the top-level permissions flags set for the borrower. For example,
170 if a user has the "editcatalogue" permission,
171 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
172 the value "1".
174 =cut
176 sub GetMemberDetails {
177 my ( $borrowernumber, $cardnumber ) = @_;
178 my $dbh = C4::Context->dbh;
179 my $query;
180 my $sth;
181 if ($borrowernumber) {
182 $sth = $dbh->prepare("
183 SELECT borrowers.*,
184 category_type,
185 categories.description,
186 categories.BlockExpiredPatronOpacActions,
187 reservefee,
188 enrolmentperiod
189 FROM borrowers
190 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
191 WHERE borrowernumber = ?
193 $sth->execute($borrowernumber);
195 elsif ($cardnumber) {
196 $sth = $dbh->prepare("
197 SELECT borrowers.*,
198 category_type,
199 categories.description,
200 categories.BlockExpiredPatronOpacActions,
201 reservefee,
202 enrolmentperiod
203 FROM borrowers
204 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
205 WHERE cardnumber = ?
207 $sth->execute($cardnumber);
209 else {
210 return;
212 my $borrower = $sth->fetchrow_hashref;
213 return unless $borrower;
214 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
215 $borrower->{'amountoutstanding'} = $amount;
216 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
217 my $flags = patronflags( $borrower);
218 my $accessflagshash;
220 $sth = $dbh->prepare("select bit,flag from userflags");
221 $sth->execute;
222 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
223 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
224 $accessflagshash->{$flag} = 1;
227 $borrower->{'flags'} = $flags;
228 $borrower->{'authflags'} = $accessflagshash;
230 # Handle setting the true behavior for BlockExpiredPatronOpacActions
231 $borrower->{'BlockExpiredPatronOpacActions'} =
232 C4::Context->preference('BlockExpiredPatronOpacActions')
233 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
235 $borrower->{'is_expired'} = 0;
236 $borrower->{'is_expired'} = 1 if
237 defined($borrower->{dateexpiry}) &&
238 $borrower->{'dateexpiry'} ne '0000-00-00' &&
239 Date_to_Days( Today() ) >
240 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
242 return ($borrower); #, $flags, $accessflagshash);
245 =head2 patronflags
247 $flags = &patronflags($patron);
249 This function is not exported.
251 The following will be set where applicable:
252 $flags->{CHARGES}->{amount} Amount of debt
253 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
254 $flags->{CHARGES}->{message} Message -- deprecated
256 $flags->{CREDITS}->{amount} Amount of credit
257 $flags->{CREDITS}->{message} Message -- deprecated
259 $flags->{ GNA } Patron has no valid address
260 $flags->{ GNA }->{noissues} Set for each GNA
261 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
263 $flags->{ LOST } Patron's card reported lost
264 $flags->{ LOST }->{noissues} Set for each LOST
265 $flags->{ LOST }->{message} Message -- deprecated
267 $flags->{DBARRED} Set if patron debarred, no access
268 $flags->{DBARRED}->{noissues} Set for each DBARRED
269 $flags->{DBARRED}->{message} Message -- deprecated
271 $flags->{ NOTES }
272 $flags->{ NOTES }->{message} The note itself. NOT deprecated
274 $flags->{ ODUES } Set if patron has overdue books.
275 $flags->{ ODUES }->{message} "Yes" -- deprecated
276 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
277 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
279 $flags->{WAITING} Set if any of patron's reserves are available
280 $flags->{WAITING}->{message} Message -- deprecated
281 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
283 =over
285 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
286 overdue items. Its elements are references-to-hash, each describing an
287 overdue item. The keys are selected fields from the issues, biblio,
288 biblioitems, and items tables of the Koha database.
290 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
291 the overdue items, one per line. Deprecated.
293 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
294 available items. Each element is a reference-to-hash whose keys are
295 fields from the reserves table of the Koha database.
297 =back
299 All the "message" fields that include language generated in this function are deprecated,
300 because such strings belong properly in the display layer.
302 The "message" field that comes from the DB is OK.
304 =cut
306 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
307 # FIXME rename this function.
308 sub patronflags {
309 my %flags;
310 my ( $patroninformation) = @_;
311 my $dbh=C4::Context->dbh;
312 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
313 if ( $owing > 0 ) {
314 my %flaginfo;
315 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
316 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
317 $flaginfo{'amount'} = sprintf "%.02f", $owing;
318 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
319 $flaginfo{'noissues'} = 1;
321 $flags{'CHARGES'} = \%flaginfo;
323 elsif ( $balance < 0 ) {
324 my %flaginfo;
325 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
326 $flaginfo{'amount'} = sprintf "%.02f", $balance;
327 $flags{'CREDITS'} = \%flaginfo;
329 if ( $patroninformation->{'gonenoaddress'}
330 && $patroninformation->{'gonenoaddress'} == 1 )
332 my %flaginfo;
333 $flaginfo{'message'} = 'Borrower has no valid address.';
334 $flaginfo{'noissues'} = 1;
335 $flags{'GNA'} = \%flaginfo;
337 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
338 my %flaginfo;
339 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
340 $flaginfo{'noissues'} = 1;
341 $flags{'LOST'} = \%flaginfo;
343 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
344 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
345 my %flaginfo;
346 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
347 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
348 $flaginfo{'noissues'} = 1;
349 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
350 $flags{'DBARRED'} = \%flaginfo;
353 if ( $patroninformation->{'borrowernotes'}
354 && $patroninformation->{'borrowernotes'} )
356 my %flaginfo;
357 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
358 $flags{'NOTES'} = \%flaginfo;
360 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
361 if ( $odues && $odues > 0 ) {
362 my %flaginfo;
363 $flaginfo{'message'} = "Yes";
364 $flaginfo{'itemlist'} = $itemsoverdue;
365 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
366 @$itemsoverdue )
368 $flaginfo{'itemlisttext'} .=
369 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
371 $flags{'ODUES'} = \%flaginfo;
373 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
374 my $nowaiting = scalar @itemswaiting;
375 if ( $nowaiting > 0 ) {
376 my %flaginfo;
377 $flaginfo{'message'} = "Reserved items available";
378 $flaginfo{'itemlist'} = \@itemswaiting;
379 $flags{'WAITING'} = \%flaginfo;
381 return ( \%flags );
385 =head2 GetMember
387 $borrower = &GetMember(%information);
389 Retrieve the first patron record meeting on criteria listed in the
390 C<%information> hash, which should contain one or more
391 pairs of borrowers column names and values, e.g.,
393 $borrower = GetMember(borrowernumber => id);
395 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
396 the C<borrowers> table in the Koha database.
398 FIXME: GetMember() is used throughout the code as a lookup
399 on a unique key such as the borrowernumber, but this meaning is not
400 enforced in the routine itself.
402 =cut
405 sub GetMember {
406 my ( %information ) = @_;
407 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
408 #passing mysql's kohaadmin?? Makes no sense as a query
409 return;
411 my $dbh = C4::Context->dbh;
412 my $select =
413 q{SELECT borrowers.*, categories.category_type, categories.description
414 FROM borrowers
415 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
416 my $more_p = 0;
417 my @values = ();
418 for (keys %information ) {
419 if ($more_p) {
420 $select .= ' AND ';
422 else {
423 $more_p++;
426 if (defined $information{$_}) {
427 $select .= "$_ = ?";
428 push @values, $information{$_};
430 else {
431 $select .= "$_ IS NULL";
434 $debug && warn $select, " ",values %information;
435 my $sth = $dbh->prepare("$select");
436 $sth->execute(@values);
437 my $data = $sth->fetchall_arrayref({});
438 #FIXME interface to this routine now allows generation of a result set
439 #so whole array should be returned but bowhere in the current code expects this
440 if (@{$data} ) {
441 return $data->[0];
444 return;
447 =head2 IsMemberBlocked
449 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
451 Returns whether a patron is restricted or has overdue items that may result
452 in a block of circulation privileges.
454 C<$block_status> can have the following values:
456 1 if the patron is currently restricted, in which case
457 C<$count> is the expiration date (9999-12-31 for indefinite)
459 -1 if the patron has overdue items, in which case C<$count> is the number of them
461 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
463 Existing active restrictions are checked before current overdue items.
465 =cut
467 sub IsMemberBlocked {
468 my $borrowernumber = shift;
469 my $dbh = C4::Context->dbh;
471 my $blockeddate = Koha::Patron::Debarments::IsDebarred($borrowernumber);
473 return ( 1, $blockeddate ) if $blockeddate;
475 # if he have late issues
476 my $sth = $dbh->prepare(
477 "SELECT COUNT(*) as latedocs
478 FROM issues
479 WHERE borrowernumber = ?
480 AND date_due < now()"
482 $sth->execute($borrowernumber);
483 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
485 return ( -1, $latedocs ) if $latedocs > 0;
487 return ( 0, 0 );
490 =head2 GetMemberIssuesAndFines
492 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
494 Returns aggregate data about items borrowed by the patron with the
495 given borrowernumber.
497 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
498 number of overdue items the patron currently has borrowed. C<$issue_count> is the
499 number of books the patron currently has borrowed. C<$total_fines> is
500 the total fine currently due by the borrower.
502 =cut
505 sub GetMemberIssuesAndFines {
506 my ( $borrowernumber ) = @_;
507 my $dbh = C4::Context->dbh;
508 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
510 $debug and warn $query."\n";
511 my $sth = $dbh->prepare($query);
512 $sth->execute($borrowernumber);
513 my $issue_count = $sth->fetchrow_arrayref->[0];
515 $sth = $dbh->prepare(
516 "SELECT COUNT(*) FROM issues
517 WHERE borrowernumber = ?
518 AND date_due < now()"
520 $sth->execute($borrowernumber);
521 my $overdue_count = $sth->fetchrow_arrayref->[0];
523 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
524 $sth->execute($borrowernumber);
525 my $total_fines = $sth->fetchrow_arrayref->[0];
527 return ($overdue_count, $issue_count, $total_fines);
531 =head2 columns
533 my @columns = C4::Member::columns();
535 Returns an array of borrowers' table columns on success,
536 and an empty array on failure.
538 =cut
540 sub columns {
542 # Pure ANSI SQL goodness.
543 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
545 # Get the database handle.
546 my $dbh = C4::Context->dbh;
548 # Run the SQL statement to load STH's readonly properties.
549 my $sth = $dbh->prepare($sql);
550 my $rv = $sth->execute();
552 # This only fails if the table doesn't exist.
553 # This will always be called AFTER an install or upgrade,
554 # so borrowers will exist!
555 my @data;
556 if ($sth->{NUM_OF_FIELDS}>0) {
557 @data = @{$sth->{NAME}};
559 else {
560 @data = ();
562 return @data;
566 =head2 ModMember
568 my $success = ModMember(borrowernumber => $borrowernumber,
569 [ field => value ]... );
571 Modify borrower's data. All date fields should ALREADY be in ISO format.
573 return :
574 true on success, or false on failure
576 =cut
578 sub ModMember {
579 my (%data) = @_;
580 # test to know if you must update or not the borrower password
581 if (exists $data{password}) {
582 if ($data{password} eq '****' or $data{password} eq '') {
583 delete $data{password};
584 } else {
585 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
586 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
587 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
589 $data{password} = hash_password($data{password});
593 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
595 # get only the columns of a borrower
596 my $schema = Koha::Database->new()->schema;
597 my @columns = $schema->source('Borrower')->columns;
598 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
599 delete $new_borrower->{flags};
601 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
602 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
603 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
604 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
605 $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
607 my $rs = $schema->resultset('Borrower')->search({
608 borrowernumber => $new_borrower->{borrowernumber},
611 my $execute_success = $rs->update($new_borrower);
612 if ($execute_success ne '0E0') { # only proceed if the update was a success
613 # If the patron changes to a category with enrollment fee, we add a fee
614 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
615 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
616 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
620 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
621 # cronjob will use for syncing with NL
622 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
623 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
624 'synctype' => 'norwegianpatrondb',
625 'borrowernumber' => $data{'borrowernumber'}
627 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
628 # we can sync as changed. And the "new sync" will pick up all changes since
629 # the patron was created anyway.
630 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
631 $borrowersync->update( { 'syncstatus' => 'edited' } );
633 # Set the value of 'sync'
634 $borrowersync->update( { 'sync' => $data{'sync'} } );
635 # Try to do the live sync
636 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
639 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
641 return $execute_success;
644 =head2 AddMember
646 $borrowernumber = &AddMember(%borrower);
648 insert new borrower into table
650 (%borrower keys are database columns. Database columns could be
651 different in different versions. Please look into database for correct
652 column names.)
654 Returns the borrowernumber upon success
656 Returns as undef upon any db error without further processing
658 =cut
661 sub AddMember {
662 my (%data) = @_;
663 my $dbh = C4::Context->dbh;
664 my $schema = Koha::Database->new()->schema;
666 # generate a proper login if none provided
667 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
668 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
670 # add expiration date if it isn't already there
671 unless ( $data{'dateexpiry'} ) {
672 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
675 # add enrollment date if it isn't already there
676 unless ( $data{'dateenrolled'} ) {
677 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
680 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
681 $data{'privacy'} =
682 $patron_category->default_privacy() eq 'default' ? 1
683 : $patron_category->default_privacy() eq 'never' ? 2
684 : $patron_category->default_privacy() eq 'forever' ? 0
685 : undef;
687 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
689 # Make a copy of the plain text password for later use
690 my $plain_text_password = $data{'password'};
692 # create a disabled account if no password provided
693 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
695 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
696 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
697 $data{'debarred'} = undef if ( not $data{'debarred'} );
698 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
700 # get only the columns of Borrower
701 my @columns = $schema->source('Borrower')->columns;
702 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
703 delete $new_member->{borrowernumber};
705 my $rs = $schema->resultset('Borrower');
706 $data{borrowernumber} = $rs->create($new_member)->id;
708 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
709 # cronjob will use for syncing with NL
710 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
711 Koha::Database->new->schema->resultset('BorrowerSync')->create({
712 'borrowernumber' => $data{'borrowernumber'},
713 'synctype' => 'norwegianpatrondb',
714 'sync' => 1,
715 'syncstatus' => 'new',
716 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
720 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
721 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
723 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
725 return $data{borrowernumber};
728 =head2 Check_Userid
730 my $uniqueness = Check_Userid($userid,$borrowernumber);
732 $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 != '').
734 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.
736 return :
737 0 for not unique (i.e. this $userid already exists)
738 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
740 =cut
742 sub Check_Userid {
743 my ( $uid, $borrowernumber ) = @_;
745 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
747 return 0 if ( $uid eq C4::Context->config('user') );
749 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
751 my $params;
752 $params->{userid} = $uid;
753 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
755 my $count = $rs->count( $params );
757 return $count ? 0 : 1;
760 =head2 Generate_Userid
762 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
764 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
766 $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.
768 return :
769 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).
771 =cut
773 sub Generate_Userid {
774 my ($borrowernumber, $firstname, $surname) = @_;
775 my $newuid;
776 my $offset = 0;
777 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
778 do {
779 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
780 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
781 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
782 $newuid = unac_string('utf-8',$newuid);
783 $newuid .= $offset unless $offset == 0;
784 $offset++;
786 } while (!Check_Userid($newuid,$borrowernumber));
788 return $newuid;
791 sub changepassword {
792 my ( $uid, $member, $digest ) = @_;
793 my $dbh = C4::Context->dbh;
795 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
796 #Then we need to tell the user and have them create a new one.
797 my $resultcode;
798 my $sth =
799 $dbh->prepare(
800 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
801 $sth->execute( $uid, $member );
802 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
803 $resultcode=0;
805 else {
806 #Everything is good so we can update the information.
807 $sth =
808 $dbh->prepare(
809 "update borrowers set userid=?, password=? where borrowernumber=?");
810 $sth->execute( $uid, $digest, $member );
811 $resultcode=1;
814 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
815 return $resultcode;
820 =head2 fixup_cardnumber
822 Warning: The caller is responsible for locking the members table in write
823 mode, to avoid database corruption.
825 =cut
827 use vars qw( @weightings );
828 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
830 sub fixup_cardnumber {
831 my ($cardnumber) = @_;
832 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
834 # Find out whether member numbers should be generated
835 # automatically. Should be either "1" or something else.
836 # Defaults to "0", which is interpreted as "no".
838 # if ($cardnumber !~ /\S/ && $autonumber_members) {
839 ($autonumber_members) or return $cardnumber;
840 my $checkdigit = C4::Context->preference('checkdigit');
841 my $dbh = C4::Context->dbh;
842 if ( $checkdigit and $checkdigit eq 'katipo' ) {
844 # if checkdigit is selected, calculate katipo-style cardnumber.
845 # otherwise, just use the max()
846 # purpose: generate checksum'd member numbers.
847 # We'll assume we just got the max value of digits 2-8 of member #'s
848 # from the database and our job is to increment that by one,
849 # determine the 1st and 9th digits and return the full string.
850 my $sth = $dbh->prepare(
851 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
853 $sth->execute;
854 my $data = $sth->fetchrow_hashref;
855 $cardnumber = $data->{new_num};
856 if ( !$cardnumber ) { # If DB has no values,
857 $cardnumber = 1000000; # start at 1000000
858 } else {
859 $cardnumber += 1;
862 my $sum = 0;
863 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
864 # read weightings, left to right, 1 char at a time
865 my $temp1 = $weightings[$i];
867 # sequence left to right, 1 char at a time
868 my $temp2 = substr( $cardnumber, $i, 1 );
870 # mult each char 1-7 by its corresponding weighting
871 $sum += $temp1 * $temp2;
874 my $rem = ( $sum % 11 );
875 $rem = 'X' if $rem == 10;
877 return "V$cardnumber$rem";
878 } else {
880 my $sth = $dbh->prepare(
881 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
883 $sth->execute;
884 my ($result) = $sth->fetchrow;
885 return $result + 1;
887 return $cardnumber; # just here as a fallback/reminder
890 =head2 GetPendingIssues
892 my $issues = &GetPendingIssues(@borrowernumber);
894 Looks up what the patron with the given borrowernumber has borrowed.
896 C<&GetPendingIssues> returns a
897 reference-to-array where each element is a reference-to-hash; the
898 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
899 The keys include C<biblioitems> fields except marc and marcxml.
901 =cut
903 sub GetPendingIssues {
904 my @borrowernumbers = @_;
906 unless (@borrowernumbers ) { # return a ref_to_array
907 return \@borrowernumbers; # to not cause surprise to caller
910 # Borrowers part of the query
911 my $bquery = '';
912 for (my $i = 0; $i < @borrowernumbers; $i++) {
913 $bquery .= ' issues.borrowernumber = ?';
914 if ($i < $#borrowernumbers ) {
915 $bquery .= ' OR';
919 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
920 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
921 # FIXME: circ/ciculation.pl tries to sort by timestamp!
922 # FIXME: namespace collision: other collisions possible.
923 # FIXME: most of this data isn't really being used by callers.
924 my $query =
925 "SELECT issues.*,
926 items.*,
927 biblio.*,
928 biblioitems.volume,
929 biblioitems.number,
930 biblioitems.itemtype,
931 biblioitems.isbn,
932 biblioitems.issn,
933 biblioitems.publicationyear,
934 biblioitems.publishercode,
935 biblioitems.volumedate,
936 biblioitems.volumedesc,
937 biblioitems.lccn,
938 biblioitems.url,
939 borrowers.firstname,
940 borrowers.surname,
941 borrowers.cardnumber,
942 issues.timestamp AS timestamp,
943 issues.renewals AS renewals,
944 issues.borrowernumber AS borrowernumber,
945 items.renewals AS totalrenewals
946 FROM issues
947 LEFT JOIN items ON items.itemnumber = issues.itemnumber
948 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
949 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
950 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
951 WHERE
952 $bquery
953 ORDER BY issues.issuedate"
956 my $sth = C4::Context->dbh->prepare($query);
957 $sth->execute(@borrowernumbers);
958 my $data = $sth->fetchall_arrayref({});
959 my $today = dt_from_string;
960 foreach (@{$data}) {
961 if ($_->{issuedate}) {
962 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
964 $_->{date_due_sql} = $_->{date_due};
965 # FIXME no need to have this value
966 $_->{date_due} or next;
967 $_->{date_due_sql} = $_->{date_due};
968 # FIXME no need to have this value
969 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
970 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
971 $_->{overdue} = 1;
974 return $data;
977 =head2 GetAllIssues
979 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
981 Looks up what the patron with the given borrowernumber has borrowed,
982 and sorts the results.
984 C<$sortkey> is the name of a field on which to sort the results. This
985 should be the name of a field in the C<issues>, C<biblio>,
986 C<biblioitems>, or C<items> table in the Koha database.
988 C<$limit> is the maximum number of results to return.
990 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
991 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
992 C<items> tables of the Koha database.
994 =cut
997 sub GetAllIssues {
998 my ( $borrowernumber, $order, $limit ) = @_;
1000 return unless $borrowernumber;
1001 $order = 'date_due desc' unless $order;
1003 my $dbh = C4::Context->dbh;
1004 my $query =
1005 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1006 FROM issues
1007 LEFT JOIN items on items.itemnumber=issues.itemnumber
1008 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1009 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1010 WHERE borrowernumber=?
1011 UNION ALL
1012 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1013 FROM old_issues
1014 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1015 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1016 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1017 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1018 order by ' . $order;
1019 if ($limit) {
1020 $query .= " limit $limit";
1023 my $sth = $dbh->prepare($query);
1024 $sth->execute( $borrowernumber, $borrowernumber );
1025 return $sth->fetchall_arrayref( {} );
1029 =head2 GetMemberAccountRecords
1031 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1033 Looks up accounting data for the patron with the given borrowernumber.
1035 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1036 reference-to-array, where each element is a reference-to-hash; the
1037 keys are the fields of the C<accountlines> table in the Koha database.
1038 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1039 total amount outstanding for all of the account lines.
1041 =cut
1043 sub GetMemberAccountRecords {
1044 my ($borrowernumber) = @_;
1045 my $dbh = C4::Context->dbh;
1046 my @acctlines;
1047 my $numlines = 0;
1048 my $strsth = qq(
1049 SELECT *
1050 FROM accountlines
1051 WHERE borrowernumber=?);
1052 $strsth.=" ORDER BY accountlines_id desc";
1053 my $sth= $dbh->prepare( $strsth );
1054 $sth->execute( $borrowernumber );
1056 my $total = 0;
1057 while ( my $data = $sth->fetchrow_hashref ) {
1058 if ( $data->{itemnumber} ) {
1059 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1060 $data->{biblionumber} = $biblio->{biblionumber};
1061 $data->{title} = $biblio->{title};
1063 $acctlines[$numlines] = $data;
1064 $numlines++;
1065 $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1067 $total /= 1000;
1068 return ( $total, \@acctlines,$numlines);
1071 =head2 GetMemberAccountBalance
1073 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1075 Calculates amount immediately owing by the patron - non-issue charges.
1076 Based on GetMemberAccountRecords.
1077 Charges exempt from non-issue are:
1078 * Res (reserves)
1079 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1080 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1082 =cut
1084 sub GetMemberAccountBalance {
1085 my ($borrowernumber) = @_;
1087 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1089 my @not_fines;
1090 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1091 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1092 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1093 my $dbh = C4::Context->dbh;
1094 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1095 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1097 my %not_fine = map {$_ => 1} @not_fines;
1099 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1100 my $other_charges = 0;
1101 foreach (@$acctlines) {
1102 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1105 return ( $total, $total - $other_charges, $other_charges);
1108 =head2 GetBorNotifyAcctRecord
1110 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1112 Looks up accounting data for the patron with the given borrowernumber per file number.
1114 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1115 reference-to-array, where each element is a reference-to-hash; the
1116 keys are the fields of the C<accountlines> table in the Koha database.
1117 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1118 total amount outstanding for all of the account lines.
1120 =cut
1122 sub GetBorNotifyAcctRecord {
1123 my ( $borrowernumber, $notifyid ) = @_;
1124 my $dbh = C4::Context->dbh;
1125 my @acctlines;
1126 my $numlines = 0;
1127 my $sth = $dbh->prepare(
1128 "SELECT *
1129 FROM accountlines
1130 WHERE borrowernumber=?
1131 AND notify_id=?
1132 AND amountoutstanding != '0'
1133 ORDER BY notify_id,accounttype
1136 $sth->execute( $borrowernumber, $notifyid );
1137 my $total = 0;
1138 while ( my $data = $sth->fetchrow_hashref ) {
1139 if ( $data->{itemnumber} ) {
1140 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1141 $data->{biblionumber} = $biblio->{biblionumber};
1142 $data->{title} = $biblio->{title};
1144 $acctlines[$numlines] = $data;
1145 $numlines++;
1146 $total += int(100 * $data->{'amountoutstanding'});
1148 $total /= 100;
1149 return ( $total, \@acctlines, $numlines );
1152 =head2 checkuniquemember (OUEST-PROVENCE)
1154 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1156 Checks that a member exists or not in the database.
1158 C<&result> is nonzero (=exist) or 0 (=does not exist)
1159 C<&categorycode> is from categorycode table
1160 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1161 C<&surname> is the surname
1162 C<&firstname> is the firstname (only if collectivity=0)
1163 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1165 =cut
1167 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1168 # This is especially true since first name is not even a required field.
1170 sub checkuniquemember {
1171 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1172 my $dbh = C4::Context->dbh;
1173 my $request = ($collectivity) ?
1174 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1175 ($dateofbirth) ?
1176 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1177 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1178 my $sth = $dbh->prepare($request);
1179 if ($collectivity) {
1180 $sth->execute( uc($surname) );
1181 } elsif($dateofbirth){
1182 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1183 }else{
1184 $sth->execute( uc($surname), ucfirst($firstname));
1186 my @data = $sth->fetchrow;
1187 ( $data[0] ) and return $data[0], $data[1];
1188 return 0;
1191 sub checkcardnumber {
1192 my ( $cardnumber, $borrowernumber ) = @_;
1194 # If cardnumber is null, we assume they're allowed.
1195 return 0 unless defined $cardnumber;
1197 my $dbh = C4::Context->dbh;
1198 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1199 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1200 my $sth = $dbh->prepare($query);
1201 $sth->execute(
1202 $cardnumber,
1203 ( $borrowernumber ? $borrowernumber : () )
1206 return 1 if $sth->fetchrow_hashref;
1208 my ( $min_length, $max_length ) = get_cardnumber_length();
1209 return 2
1210 if length $cardnumber > $max_length
1211 or length $cardnumber < $min_length;
1213 return 0;
1216 =head2 get_cardnumber_length
1218 my ($min, $max) = C4::Members::get_cardnumber_length()
1220 Returns the minimum and maximum length for patron cardnumbers as
1221 determined by the CardnumberLength system preference, the
1222 BorrowerMandatoryField system preference, and the width of the
1223 database column.
1225 =cut
1227 sub get_cardnumber_length {
1228 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1229 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1230 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1231 # Is integer and length match
1232 if ( $cardnumber_length =~ m|^\d+$| ) {
1233 $min = $max = $cardnumber_length
1234 if $cardnumber_length >= $min
1235 and $cardnumber_length <= $max;
1237 # Else assuming it is a range
1238 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1239 $min = $1 if $1 and $min < $1;
1240 $max = $2 if $2 and $max > $2;
1244 return ( $min, $max );
1247 =head2 GetFirstValidEmailAddress
1249 $email = GetFirstValidEmailAddress($borrowernumber);
1251 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1252 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1253 addresses.
1255 =cut
1257 sub GetFirstValidEmailAddress {
1258 my $borrowernumber = shift;
1259 my $dbh = C4::Context->dbh;
1260 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1261 $sth->execute( $borrowernumber );
1262 my $data = $sth->fetchrow_hashref;
1264 if ($data->{'email'}) {
1265 return $data->{'email'};
1266 } elsif ($data->{'emailpro'}) {
1267 return $data->{'emailpro'};
1268 } elsif ($data->{'B_email'}) {
1269 return $data->{'B_email'};
1270 } else {
1271 return '';
1275 =head2 GetNoticeEmailAddress
1277 $email = GetNoticeEmailAddress($borrowernumber);
1279 Return the email address of borrower used for notices, given the borrowernumber.
1280 Returns the empty string if no email address.
1282 =cut
1284 sub GetNoticeEmailAddress {
1285 my $borrowernumber = shift;
1287 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1288 # if syspref is set to 'first valid' (value == OFF), look up email address
1289 if ( $which_address eq 'OFF' ) {
1290 return GetFirstValidEmailAddress($borrowernumber);
1292 # specified email address field
1293 my $dbh = C4::Context->dbh;
1294 my $sth = $dbh->prepare( qq{
1295 SELECT $which_address AS primaryemail
1296 FROM borrowers
1297 WHERE borrowernumber=?
1298 } );
1299 $sth->execute($borrowernumber);
1300 my $data = $sth->fetchrow_hashref;
1301 return $data->{'primaryemail'} || '';
1304 =head2 GetExpiryDate
1306 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1308 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1309 Return date is also in ISO format.
1311 =cut
1313 sub GetExpiryDate {
1314 my ( $categorycode, $dateenrolled ) = @_;
1315 my $enrolments;
1316 if ($categorycode) {
1317 my $dbh = C4::Context->dbh;
1318 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1319 $sth->execute($categorycode);
1320 $enrolments = $sth->fetchrow_hashref;
1322 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1323 my @date = split (/-/,$dateenrolled);
1324 if($enrolments->{enrolmentperiod}){
1325 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1326 }else{
1327 return $enrolments->{enrolmentperioddate};
1331 =head2 GetUpcomingMembershipExpires
1333 my $upcoming_mem_expires = GetUpcomingMembershipExpires();
1335 =cut
1337 sub GetUpcomingMembershipExpires {
1338 my $dbh = C4::Context->dbh;
1339 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1340 my $dateexpiry = output_pref({ dt => (dt_from_string()->add( days => $days)), dateformat => 'iso', dateonly => 1 });
1342 my $query = "
1343 SELECT borrowers.*, categories.description,
1344 branches.branchname, branches.branchemail FROM borrowers
1345 LEFT JOIN branches on borrowers.branchcode = branches.branchcode
1346 LEFT JOIN categories on borrowers.categorycode = categories.categorycode
1347 WHERE dateexpiry = ?;
1349 my $sth = $dbh->prepare($query);
1350 $sth->execute($dateexpiry);
1351 my $results = $sth->fetchall_arrayref({});
1352 return $results;
1355 =head2 GetborCatFromCatType
1357 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1359 Looks up the different types of borrowers in the database. Returns two
1360 elements: a reference-to-array, which lists the borrower category
1361 codes, and a reference-to-hash, which maps the borrower category codes
1362 to category descriptions.
1364 =cut
1367 sub GetborCatFromCatType {
1368 my ( $category_type, $action, $no_branch_limit ) = @_;
1370 my $branch_limit = $no_branch_limit
1372 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1374 # FIXME - This API seems both limited and dangerous.
1375 my $dbh = C4::Context->dbh;
1377 my $request = qq{
1378 SELECT categories.categorycode, categories.description
1379 FROM categories
1381 $request .= qq{
1382 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1383 } if $branch_limit;
1384 if($action) {
1385 $request .= " $action ";
1386 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1387 } else {
1388 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1390 $request .= " ORDER BY categorycode";
1392 my $sth = $dbh->prepare($request);
1393 $sth->execute(
1394 $action ? $category_type : (),
1395 $branch_limit ? $branch_limit : ()
1398 my %labels;
1399 my @codes;
1401 while ( my $data = $sth->fetchrow_hashref ) {
1402 push @codes, $data->{'categorycode'};
1403 $labels{ $data->{'categorycode'} } = $data->{'description'};
1405 $sth->finish;
1406 return ( \@codes, \%labels );
1409 =head2 GetBorrowercategory
1411 $hashref = &GetBorrowercategory($categorycode);
1413 Given the borrower's category code, the function returns the corresponding
1414 data hashref for a comprehensive information display.
1416 =cut
1418 sub GetBorrowercategory {
1419 my ($catcode) = @_;
1420 my $dbh = C4::Context->dbh;
1421 if ($catcode){
1422 my $sth =
1423 $dbh->prepare(
1424 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1425 FROM categories
1426 WHERE categorycode = ?"
1428 $sth->execute($catcode);
1429 my $data =
1430 $sth->fetchrow_hashref;
1431 return $data;
1433 return;
1434 } # sub getborrowercategory
1437 =head2 GetBorrowerCategorycode
1439 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1441 Given the borrowernumber, the function returns the corresponding categorycode
1443 =cut
1445 sub GetBorrowerCategorycode {
1446 my ( $borrowernumber ) = @_;
1447 my $dbh = C4::Context->dbh;
1448 my $sth = $dbh->prepare( qq{
1449 SELECT categorycode
1450 FROM borrowers
1451 WHERE borrowernumber = ?
1452 } );
1453 $sth->execute( $borrowernumber );
1454 return $sth->fetchrow;
1457 =head2 GetBorrowercategoryList
1459 $arrayref_hashref = &GetBorrowercategoryList;
1460 If no category code provided, the function returns all the categories.
1462 =cut
1464 sub GetBorrowercategoryList {
1465 my $no_branch_limit = @_ ? shift : 0;
1466 my $branch_limit = $no_branch_limit
1468 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1469 my $dbh = C4::Context->dbh;
1470 my $query = "SELECT categories.* FROM categories";
1471 $query .= qq{
1472 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1473 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1474 } if $branch_limit;
1475 $query .= " ORDER BY description";
1476 my $sth = $dbh->prepare( $query );
1477 $sth->execute( $branch_limit ? $branch_limit : () );
1478 my $data = $sth->fetchall_arrayref( {} );
1479 $sth->finish;
1480 return $data;
1481 } # sub getborrowercategory
1483 =head2 GetAge
1485 $dateofbirth,$date = &GetAge($date);
1487 this function return the borrowers age with the value of dateofbirth
1489 =cut
1492 sub GetAge{
1493 my ( $date, $date_ref ) = @_;
1495 if ( not defined $date_ref ) {
1496 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1499 my ( $year1, $month1, $day1 ) = split /-/, $date;
1500 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1502 my $age = $year2 - $year1;
1503 if ( $month1 . $day1 > $month2 . $day2 ) {
1504 $age--;
1507 return $age;
1508 } # sub get_age
1510 =head2 SetAge
1512 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1513 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1514 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1516 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1517 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1519 This function sets the borrower's dateofbirth to match the given age.
1520 Optionally relative to the given $datetime_reference.
1522 @PARAM1 koha.borrowers-object
1523 @PARAM2 DateTime::Duration-object as the desired age
1524 OR a ISO 8601 Date. (To make the API more pleasant)
1525 @PARAM3 DateTime-object as the relative date, defaults to now().
1526 RETURNS The given borrower reference @PARAM1.
1527 DIES If there was an error with the ISO Date handling.
1529 =cut
1532 sub SetAge{
1533 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1534 $datetime_ref = DateTime->now() unless $datetime_ref;
1536 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1537 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1538 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1540 else {
1541 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1545 my $new_datetime_ref = $datetime_ref->clone();
1546 $new_datetime_ref->subtract_duration( $datetimeduration );
1548 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1550 return $borrower;
1551 } # sub SetAge
1553 =head2 GetSortDetails (OUEST-PROVENCE)
1555 ($lib) = &GetSortDetails($category,$sortvalue);
1557 Returns the authorized value details
1558 C<&$lib>return value of authorized value details
1559 C<&$sortvalue>this is the value of authorized value
1560 C<&$category>this is the value of authorized value category
1562 =cut
1564 sub GetSortDetails {
1565 my ( $category, $sortvalue ) = @_;
1566 my $dbh = C4::Context->dbh;
1567 my $query = qq|SELECT lib
1568 FROM authorised_values
1569 WHERE category=?
1570 AND authorised_value=? |;
1571 my $sth = $dbh->prepare($query);
1572 $sth->execute( $category, $sortvalue );
1573 my $lib = $sth->fetchrow;
1574 return ($lib) if ($lib);
1575 return ($sortvalue) unless ($lib);
1578 =head2 MoveMemberToDeleted
1580 $result = &MoveMemberToDeleted($borrowernumber);
1582 Copy the record from borrowers to deletedborrowers table.
1583 The routine returns 1 for success, undef for failure.
1585 =cut
1587 sub MoveMemberToDeleted {
1588 my ($member) = shift or return;
1590 my $schema = Koha::Database->new()->schema();
1591 my $borrowers_rs = $schema->resultset('Borrower');
1592 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1593 my $borrower = $borrowers_rs->find($member);
1594 return unless $borrower;
1596 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1598 return $deleted ? 1 : undef;
1601 =head2 DelMember
1603 DelMember($borrowernumber);
1605 This function remove directly a borrower whitout writing it on deleteborrower.
1606 + Deletes reserves for the borrower
1608 =cut
1610 sub DelMember {
1611 my $dbh = C4::Context->dbh;
1612 my $borrowernumber = shift;
1613 #warn "in delmember with $borrowernumber";
1614 return unless $borrowernumber; # borrowernumber is mandatory.
1616 my $query = qq|DELETE
1617 FROM reserves
1618 WHERE borrowernumber=?|;
1619 my $sth = $dbh->prepare($query);
1620 $sth->execute($borrowernumber);
1621 $query = "
1622 DELETE
1623 FROM borrowers
1624 WHERE borrowernumber = ?
1626 $sth = $dbh->prepare($query);
1627 $sth->execute($borrowernumber);
1628 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1629 return $sth->rows;
1632 =head2 HandleDelBorrower
1634 HandleDelBorrower($borrower);
1636 When a member is deleted (DelMember in Members.pm), you should call me first.
1637 This routine deletes/moves lists and entries for the deleted member/borrower.
1638 Lists owned by the borrower are deleted, but entries from the borrower to
1639 other lists are kept.
1641 =cut
1643 sub HandleDelBorrower {
1644 my ($borrower)= @_;
1645 my $query;
1646 my $dbh = C4::Context->dbh;
1648 #Delete all lists and all shares of this borrower
1649 #Consistent with the approach Koha uses on deleting individual lists
1650 #Note that entries in virtualshelfcontents added by this borrower to
1651 #lists of others will be handled by a table constraint: the borrower
1652 #is set to NULL in those entries.
1653 $query="DELETE FROM virtualshelves WHERE owner=?";
1654 $dbh->do($query,undef,($borrower));
1656 #NOTE:
1657 #We could handle the above deletes via a constraint too.
1658 #But a new BZ report 11889 has been opened to discuss another approach.
1659 #Instead of deleting we could also disown lists (based on a pref).
1660 #In that way we could save shared and public lists.
1661 #The current table constraints support that idea now.
1662 #This pref should then govern the results of other routines/methods such as
1663 #Koha::Virtualshelf->new->delete too.
1666 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1668 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1670 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1671 Returns ISO date.
1673 =cut
1675 sub ExtendMemberSubscriptionTo {
1676 my ( $borrowerid,$date) = @_;
1677 my $dbh = C4::Context->dbh;
1678 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1679 unless ($date){
1680 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1681 eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'} ), dateonly => 1, dateformat => 'iso' } ); }
1683 output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1684 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1686 my $sth = $dbh->do(<<EOF);
1687 UPDATE borrowers
1688 SET dateexpiry='$date'
1689 WHERE borrowernumber='$borrowerid'
1692 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1694 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1695 return $date if ($sth);
1696 return 0;
1699 =head2 GetTitles (OUEST-PROVENCE)
1701 ($borrowertitle)= &GetTitles();
1703 Looks up the different title . Returns array with all borrowers title
1705 =cut
1707 sub GetTitles {
1708 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1709 unshift( @borrowerTitle, "" );
1710 my $count=@borrowerTitle;
1711 if ($count == 1){
1712 return ();
1714 else {
1715 return ( \@borrowerTitle);
1719 =head2 GetHideLostItemsPreference
1721 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1723 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1724 C<&$hidelostitemspref>return value of function, 0 or 1
1726 =cut
1728 sub GetHideLostItemsPreference {
1729 my ($borrowernumber) = @_;
1730 my $dbh = C4::Context->dbh;
1731 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1732 my $sth = $dbh->prepare($query);
1733 $sth->execute($borrowernumber);
1734 my $hidelostitems = $sth->fetchrow;
1735 return $hidelostitems;
1738 =head2 GetBorrowersToExpunge
1740 $borrowers = &GetBorrowersToExpunge(
1741 not_borrowed_since => $not_borrowed_since,
1742 expired_before => $expired_before,
1743 category_code => $category_code,
1744 patron_list_id => $patron_list_id,
1745 branchcode => $branchcode
1748 This function get all borrowers based on the given criteria.
1750 =cut
1752 sub GetBorrowersToExpunge {
1754 my $params = shift;
1755 my $filterdate = $params->{'not_borrowed_since'};
1756 my $filterexpiry = $params->{'expired_before'};
1757 my $filtercategory = $params->{'category_code'};
1758 my $filterbranch = $params->{'branchcode'} ||
1759 ((C4::Context->preference('IndependentBranches')
1760 && C4::Context->userenv
1761 && !C4::Context->IsSuperLibrarian()
1762 && C4::Context->userenv->{branch})
1763 ? C4::Context->userenv->{branch}
1764 : "");
1765 my $filterpatronlist = $params->{'patron_list_id'};
1767 my $dbh = C4::Context->dbh;
1768 my $query = q|
1769 SELECT borrowers.borrowernumber,
1770 MAX(old_issues.timestamp) AS latestissue,
1771 MAX(issues.timestamp) AS currentissue
1772 FROM borrowers
1773 JOIN categories USING (categorycode)
1774 LEFT JOIN (
1775 SELECT guarantorid
1776 FROM borrowers
1777 WHERE guarantorid IS NOT NULL
1778 AND guarantorid <> 0
1779 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1780 LEFT JOIN old_issues USING (borrowernumber)
1781 LEFT JOIN issues USING (borrowernumber)|;
1782 if ( $filterpatronlist ){
1783 $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1785 $query .= q| WHERE category_type <> 'S'
1786 AND tmp.guarantorid IS NULL
1788 my @query_params;
1789 if ( $filterbranch && $filterbranch ne "" ) {
1790 $query.= " AND borrowers.branchcode = ? ";
1791 push( @query_params, $filterbranch );
1793 if ( $filterexpiry ) {
1794 $query .= " AND dateexpiry < ? ";
1795 push( @query_params, $filterexpiry );
1797 if ( $filtercategory ) {
1798 $query .= " AND categorycode = ? ";
1799 push( @query_params, $filtercategory );
1801 if ( $filterpatronlist ){
1802 $query.=" AND patron_list_id = ? ";
1803 push( @query_params, $filterpatronlist );
1805 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1806 if ( $filterdate ) {
1807 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1808 push @query_params,$filterdate;
1810 warn $query if $debug;
1812 my $sth = $dbh->prepare($query);
1813 if (scalar(@query_params)>0){
1814 $sth->execute(@query_params);
1816 else {
1817 $sth->execute;
1820 my @results;
1821 while ( my $data = $sth->fetchrow_hashref ) {
1822 push @results, $data;
1824 return \@results;
1827 =head2 GetBorrowersWhoHaveNeverBorrowed
1829 $results = &GetBorrowersWhoHaveNeverBorrowed
1831 This function get all borrowers who have never borrowed.
1833 I<$result> is a ref to an array which all elements are a hasref.
1835 =cut
1837 sub GetBorrowersWhoHaveNeverBorrowed {
1838 my $filterbranch = shift ||
1839 ((C4::Context->preference('IndependentBranches')
1840 && C4::Context->userenv
1841 && !C4::Context->IsSuperLibrarian()
1842 && C4::Context->userenv->{branch})
1843 ? C4::Context->userenv->{branch}
1844 : "");
1845 my $dbh = C4::Context->dbh;
1846 my $query = "
1847 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1848 FROM borrowers
1849 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1850 WHERE issues.borrowernumber IS NULL
1852 my @query_params;
1853 if ($filterbranch && $filterbranch ne ""){
1854 $query.=" AND borrowers.branchcode= ?";
1855 push @query_params,$filterbranch;
1857 warn $query if $debug;
1859 my $sth = $dbh->prepare($query);
1860 if (scalar(@query_params)>0){
1861 $sth->execute(@query_params);
1863 else {
1864 $sth->execute;
1867 my @results;
1868 while ( my $data = $sth->fetchrow_hashref ) {
1869 push @results, $data;
1871 return \@results;
1874 =head2 GetBorrowersWithIssuesHistoryOlderThan
1876 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1878 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1880 I<$result> is a ref to an array which all elements are a hashref.
1881 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1883 =cut
1885 sub GetBorrowersWithIssuesHistoryOlderThan {
1886 my $dbh = C4::Context->dbh;
1887 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1888 my $filterbranch = shift ||
1889 ((C4::Context->preference('IndependentBranches')
1890 && C4::Context->userenv
1891 && !C4::Context->IsSuperLibrarian()
1892 && C4::Context->userenv->{branch})
1893 ? C4::Context->userenv->{branch}
1894 : "");
1895 my $query = "
1896 SELECT count(borrowernumber) as n,borrowernumber
1897 FROM old_issues
1898 WHERE returndate < ?
1899 AND borrowernumber IS NOT NULL
1901 my @query_params;
1902 push @query_params, $date;
1903 if ($filterbranch){
1904 $query.=" AND branchcode = ?";
1905 push @query_params, $filterbranch;
1907 $query.=" GROUP BY borrowernumber ";
1908 warn $query if $debug;
1909 my $sth = $dbh->prepare($query);
1910 $sth->execute(@query_params);
1911 my @results;
1913 while ( my $data = $sth->fetchrow_hashref ) {
1914 push @results, $data;
1916 return \@results;
1919 =head2 GetBorrowersNamesAndLatestIssue
1921 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1923 this function get borrowers Names and surnames and Issue information.
1925 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1926 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1928 =cut
1930 sub GetBorrowersNamesAndLatestIssue {
1931 my $dbh = C4::Context->dbh;
1932 my @borrowernumbers=@_;
1933 my $query = "
1934 SELECT surname,lastname, phone, email,max(timestamp)
1935 FROM borrowers
1936 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1937 GROUP BY borrowernumber
1939 my $sth = $dbh->prepare($query);
1940 $sth->execute;
1941 my $results = $sth->fetchall_arrayref({});
1942 return $results;
1945 =head2 ModPrivacy
1947 my $success = ModPrivacy( $borrowernumber, $privacy );
1949 Update the privacy of a patron.
1951 return :
1952 true on success, false on failure
1954 =cut
1956 sub ModPrivacy {
1957 my $borrowernumber = shift;
1958 my $privacy = shift;
1959 return unless defined $borrowernumber;
1960 return unless $borrowernumber =~ /^\d+$/;
1962 return ModMember( borrowernumber => $borrowernumber,
1963 privacy => $privacy );
1966 =head2 IssueSlip
1968 IssueSlip($branchcode, $borrowernumber, $quickslip)
1970 Returns letter hash ( see C4::Letters::GetPreparedLetter )
1972 $quickslip is boolean, to indicate whether we want a quick slip
1974 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1976 Both slips:
1978 <<branches.*>>
1979 <<borrowers.*>>
1981 ISSUESLIP:
1983 <checkedout>
1984 <<biblio.*>>
1985 <<items.*>>
1986 <<biblioitems.*>>
1987 <<issues.*>>
1988 </checkedout>
1990 <overdue>
1991 <<biblio.*>>
1992 <<items.*>>
1993 <<biblioitems.*>>
1994 <<issues.*>>
1995 </overdue>
1997 <news>
1998 <<opac_news.*>>
1999 </news>
2001 ISSUEQSLIP:
2003 <checkedout>
2004 <<biblio.*>>
2005 <<items.*>>
2006 <<biblioitems.*>>
2007 <<issues.*>>
2008 </checkedout>
2010 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2012 =cut
2014 sub IssueSlip {
2015 my ($branch, $borrowernumber, $quickslip) = @_;
2017 # FIXME Check callers before removing this statement
2018 #return unless $borrowernumber;
2020 my @issues = @{ GetPendingIssues($borrowernumber) };
2022 for my $issue (@issues) {
2023 $issue->{date_due} = $issue->{date_due_sql};
2024 if ($quickslip) {
2025 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2026 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2027 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2028 $issue->{now} = 1;
2033 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2034 @issues = sort {
2035 my $s = $b->{timestamp} <=> $a->{timestamp};
2036 $s == 0 ?
2037 $b->{issuedate} <=> $a->{issuedate} : $s;
2038 } @issues;
2040 my ($letter_code, %repeat);
2041 if ( $quickslip ) {
2042 $letter_code = 'ISSUEQSLIP';
2043 %repeat = (
2044 'checkedout' => [ map {
2045 'biblio' => $_,
2046 'items' => $_,
2047 'biblioitems' => $_,
2048 'issues' => $_,
2049 }, grep { $_->{'now'} } @issues ],
2052 else {
2053 $letter_code = 'ISSUESLIP';
2054 %repeat = (
2055 'checkedout' => [ map {
2056 'biblio' => $_,
2057 'items' => $_,
2058 'biblioitems' => $_,
2059 'issues' => $_,
2060 }, grep { !$_->{'overdue'} } @issues ],
2062 'overdue' => [ map {
2063 'biblio' => $_,
2064 'items' => $_,
2065 'biblioitems' => $_,
2066 'issues' => $_,
2067 }, grep { $_->{'overdue'} } @issues ],
2069 'news' => [ map {
2070 $_->{'timestamp'} = $_->{'newdate'};
2071 { opac_news => $_ }
2072 } @{ GetNewsToDisplay("slip",$branch) } ],
2076 return C4::Letters::GetPreparedLetter (
2077 module => 'circulation',
2078 letter_code => $letter_code,
2079 branchcode => $branch,
2080 tables => {
2081 'branches' => $branch,
2082 'borrowers' => $borrowernumber,
2084 repeat => \%repeat,
2088 =head2 GetBorrowersWithEmail
2090 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2092 This gets a list of users and their basic details from their email address.
2093 As it's possible for multiple user to have the same email address, it provides
2094 you with all of them. If there is no userid for the user, there will be an
2095 C<undef> there. An empty list will be returned if there are no matches.
2097 =cut
2099 sub GetBorrowersWithEmail {
2100 my $email = shift;
2102 my $dbh = C4::Context->dbh;
2104 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2105 my $sth=$dbh->prepare($query);
2106 $sth->execute($email);
2107 my @result = ();
2108 while (my $ref = $sth->fetch) {
2109 push @result, $ref;
2111 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2112 return @result;
2115 =head2 AddMember_Opac
2117 =cut
2119 sub AddMember_Opac {
2120 my ( %borrower ) = @_;
2122 $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2123 if (not defined $borrower{'password'}){
2124 my $sr = new String::Random;
2125 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2126 my $password = $sr->randpattern("AAAAAAAAAA");
2127 $borrower{'password'} = $password;
2130 $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
2132 my $borrowernumber = AddMember(%borrower);
2134 return ( $borrowernumber, $borrower{'password'} );
2137 =head2 AddEnrolmentFeeIfNeeded
2139 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2141 Add enrolment fee for a patron if needed.
2143 =cut
2145 sub AddEnrolmentFeeIfNeeded {
2146 my ( $categorycode, $borrowernumber ) = @_;
2147 # check for enrollment fee & add it if needed
2148 my $dbh = C4::Context->dbh;
2149 my $sth = $dbh->prepare(q{
2150 SELECT enrolmentfee
2151 FROM categories
2152 WHERE categorycode=?
2154 $sth->execute( $categorycode );
2155 if ( $sth->err ) {
2156 warn sprintf('Database returned the following error: %s', $sth->errstr);
2157 return;
2159 my ($enrolmentfee) = $sth->fetchrow;
2160 if ($enrolmentfee && $enrolmentfee > 0) {
2161 # insert fee in patron debts
2162 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2166 =head2 HasOverdues
2168 =cut
2170 sub HasOverdues {
2171 my ( $borrowernumber ) = @_;
2173 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2174 my $sth = C4::Context->dbh->prepare( $sql );
2175 $sth->execute( $borrowernumber );
2176 my ( $count ) = $sth->fetchrow_array();
2178 return $count;
2181 =head2 DeleteExpiredOpacRegistrations
2183 Delete accounts that haven't been upgraded from the 'temporary' category
2184 Returns the number of removed patrons
2186 =cut
2188 sub DeleteExpiredOpacRegistrations {
2190 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2191 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2193 return 0 if not $category_code or not defined $delay or $delay eq q||;
2195 my $query = qq|
2196 SELECT borrowernumber
2197 FROM borrowers
2198 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2200 my $dbh = C4::Context->dbh;
2201 my $sth = $dbh->prepare($query);
2202 $sth->execute( $category_code, $delay );
2203 my $cnt=0;
2204 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2205 DelMember($borrowernumber);
2206 $cnt++;
2208 return $cnt;
2211 =head2 DeleteUnverifiedOpacRegistrations
2213 Delete all unverified self registrations in borrower_modifications,
2214 older than the specified number of days.
2216 =cut
2218 sub DeleteUnverifiedOpacRegistrations {
2219 my ( $days ) = @_;
2220 my $dbh = C4::Context->dbh;
2221 my $sql=qq|
2222 DELETE FROM borrower_modifications
2223 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2224 my $cnt=$dbh->do($sql, undef, ($days) );
2225 return $cnt eq '0E0'? 0: $cnt;
2228 sub GetOverduesForPatron {
2229 my ( $borrowernumber ) = @_;
2231 my $sql = "
2232 SELECT *
2233 FROM issues, items, biblio, biblioitems
2234 WHERE items.itemnumber=issues.itemnumber
2235 AND biblio.biblionumber = items.biblionumber
2236 AND biblio.biblionumber = biblioitems.biblionumber
2237 AND issues.borrowernumber = ?
2238 AND date_due < NOW()
2241 my $sth = C4::Context->dbh->prepare( $sql );
2242 $sth->execute( $borrowernumber );
2244 return $sth->fetchall_arrayref({});
2247 END { } # module clean-up code here (global destructor)
2251 __END__
2253 =head1 AUTHOR
2255 Koha Team
2257 =cut