Bug 16847: Remove C4::Members::GetTitles
[koha.git] / C4 / Members.pm
bloba9068096439dc933c030001d10c1f926139faa42
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 Scalar::Util qw( looks_like_number );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
36 use C4::NewsChannels; #get slip news
37 use DateTime;
38 use Koha::Database;
39 use Koha::DateUtils;
40 use Koha::Patron::Debarments qw(IsDebarred);
41 use Text::Unaccent qw( unac_string );
42 use Koha::AuthUtils qw(hash_password);
43 use Koha::Database;
44 use Koha::Holds;
45 use Koha::List::Patron;
47 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
49 use Module::Load::Conditional qw( can_load );
50 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
51 $debug && warn "Unable to load Koha::NorwegianPatronDB";
55 BEGIN {
56 $debug = $ENV{DEBUG} || 0;
57 require Exporter;
58 @ISA = qw(Exporter);
59 #Get data
60 push @EXPORT, qw(
61 &Search
62 &GetMemberDetails
63 &GetMember
65 &GetMemberIssuesAndFines
66 &GetPendingIssues
67 &GetAllIssues
69 &GetFirstValidEmailAddress
70 &GetNoticeEmailAddress
72 &GetAge
73 &GetSortDetails
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;
330 # Check the debt of the guarntees of this patron
331 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
332 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
333 if ( defined $no_issues_charge_guarantees ) {
334 my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
335 my @guarantees = $p->guarantees();
336 my $guarantees_non_issues_charges;
337 foreach my $g ( @guarantees ) {
338 my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
339 $guarantees_non_issues_charges += $n;
342 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
343 my %flaginfo;
344 $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
345 $flaginfo{'amount'} = $guarantees_non_issues_charges;
346 $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
347 $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
351 if ( $patroninformation->{'gonenoaddress'}
352 && $patroninformation->{'gonenoaddress'} == 1 )
354 my %flaginfo;
355 $flaginfo{'message'} = 'Borrower has no valid address.';
356 $flaginfo{'noissues'} = 1;
357 $flags{'GNA'} = \%flaginfo;
359 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
360 my %flaginfo;
361 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
362 $flaginfo{'noissues'} = 1;
363 $flags{'LOST'} = \%flaginfo;
365 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
366 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
367 my %flaginfo;
368 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
369 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
370 $flaginfo{'noissues'} = 1;
371 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
372 $flags{'DBARRED'} = \%flaginfo;
375 if ( $patroninformation->{'borrowernotes'}
376 && $patroninformation->{'borrowernotes'} )
378 my %flaginfo;
379 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
380 $flags{'NOTES'} = \%flaginfo;
382 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
383 if ( $odues && $odues > 0 ) {
384 my %flaginfo;
385 $flaginfo{'message'} = "Yes";
386 $flaginfo{'itemlist'} = $itemsoverdue;
387 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
388 @$itemsoverdue )
390 $flaginfo{'itemlisttext'} .=
391 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
393 $flags{'ODUES'} = \%flaginfo;
395 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
396 my $nowaiting = scalar @itemswaiting;
397 if ( $nowaiting > 0 ) {
398 my %flaginfo;
399 $flaginfo{'message'} = "Reserved items available";
400 $flaginfo{'itemlist'} = \@itemswaiting;
401 $flags{'WAITING'} = \%flaginfo;
403 return ( \%flags );
407 =head2 GetMember
409 $borrower = &GetMember(%information);
411 Retrieve the first patron record meeting on criteria listed in the
412 C<%information> hash, which should contain one or more
413 pairs of borrowers column names and values, e.g.,
415 $borrower = GetMember(borrowernumber => id);
417 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
418 the C<borrowers> table in the Koha database.
420 FIXME: GetMember() is used throughout the code as a lookup
421 on a unique key such as the borrowernumber, but this meaning is not
422 enforced in the routine itself.
424 =cut
427 sub GetMember {
428 my ( %information ) = @_;
429 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
430 #passing mysql's kohaadmin?? Makes no sense as a query
431 return;
433 my $dbh = C4::Context->dbh;
434 my $select =
435 q{SELECT borrowers.*, categories.category_type, categories.description
436 FROM borrowers
437 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
438 my $more_p = 0;
439 my @values = ();
440 for (keys %information ) {
441 if ($more_p) {
442 $select .= ' AND ';
444 else {
445 $more_p++;
448 if (defined $information{$_}) {
449 $select .= "$_ = ?";
450 push @values, $information{$_};
452 else {
453 $select .= "$_ IS NULL";
456 $debug && warn $select, " ",values %information;
457 my $sth = $dbh->prepare("$select");
458 $sth->execute(@values);
459 my $data = $sth->fetchall_arrayref({});
460 #FIXME interface to this routine now allows generation of a result set
461 #so whole array should be returned but bowhere in the current code expects this
462 if (@{$data} ) {
463 return $data->[0];
466 return;
469 =head2 IsMemberBlocked
471 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
473 Returns whether a patron is restricted or has overdue items that may result
474 in a block of circulation privileges.
476 C<$block_status> can have the following values:
478 1 if the patron is currently restricted, in which case
479 C<$count> is the expiration date (9999-12-31 for indefinite)
481 -1 if the patron has overdue items, in which case C<$count> is the number of them
483 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
485 Existing active restrictions are checked before current overdue items.
487 =cut
489 sub IsMemberBlocked {
490 my $borrowernumber = shift;
491 my $dbh = C4::Context->dbh;
493 my $blockeddate = Koha::Patron::Debarments::IsDebarred($borrowernumber);
495 return ( 1, $blockeddate ) if $blockeddate;
497 # if he have late issues
498 my $sth = $dbh->prepare(
499 "SELECT COUNT(*) as latedocs
500 FROM issues
501 WHERE borrowernumber = ?
502 AND date_due < now()"
504 $sth->execute($borrowernumber);
505 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
507 return ( -1, $latedocs ) if $latedocs > 0;
509 return ( 0, 0 );
512 =head2 GetMemberIssuesAndFines
514 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
516 Returns aggregate data about items borrowed by the patron with the
517 given borrowernumber.
519 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
520 number of overdue items the patron currently has borrowed. C<$issue_count> is the
521 number of books the patron currently has borrowed. C<$total_fines> is
522 the total fine currently due by the borrower.
524 =cut
527 sub GetMemberIssuesAndFines {
528 my ( $borrowernumber ) = @_;
529 my $dbh = C4::Context->dbh;
530 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
532 $debug and warn $query."\n";
533 my $sth = $dbh->prepare($query);
534 $sth->execute($borrowernumber);
535 my $issue_count = $sth->fetchrow_arrayref->[0];
537 $sth = $dbh->prepare(
538 "SELECT COUNT(*) FROM issues
539 WHERE borrowernumber = ?
540 AND date_due < now()"
542 $sth->execute($borrowernumber);
543 my $overdue_count = $sth->fetchrow_arrayref->[0];
545 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
546 $sth->execute($borrowernumber);
547 my $total_fines = $sth->fetchrow_arrayref->[0];
549 return ($overdue_count, $issue_count, $total_fines);
553 =head2 columns
555 my @columns = C4::Member::columns();
557 Returns an array of borrowers' table columns on success,
558 and an empty array on failure.
560 =cut
562 sub columns {
564 # Pure ANSI SQL goodness.
565 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
567 # Get the database handle.
568 my $dbh = C4::Context->dbh;
570 # Run the SQL statement to load STH's readonly properties.
571 my $sth = $dbh->prepare($sql);
572 my $rv = $sth->execute();
574 # This only fails if the table doesn't exist.
575 # This will always be called AFTER an install or upgrade,
576 # so borrowers will exist!
577 my @data;
578 if ($sth->{NUM_OF_FIELDS}>0) {
579 @data = @{$sth->{NAME}};
581 else {
582 @data = ();
584 return @data;
588 =head2 ModMember
590 my $success = ModMember(borrowernumber => $borrowernumber,
591 [ field => value ]... );
593 Modify borrower's data. All date fields should ALREADY be in ISO format.
595 return :
596 true on success, or false on failure
598 =cut
600 sub ModMember {
601 my (%data) = @_;
602 # test to know if you must update or not the borrower password
603 if (exists $data{password}) {
604 if ($data{password} eq '****' or $data{password} eq '') {
605 delete $data{password};
606 } else {
607 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
608 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
609 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
611 $data{password} = hash_password($data{password});
615 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
617 # get only the columns of a borrower
618 my $schema = Koha::Database->new()->schema;
619 my @columns = $schema->source('Borrower')->columns;
620 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
621 delete $new_borrower->{flags};
623 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
624 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
625 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
626 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
627 $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
629 my $rs = $schema->resultset('Borrower')->search({
630 borrowernumber => $new_borrower->{borrowernumber},
633 delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
635 my $execute_success = $rs->update($new_borrower);
636 if ($execute_success ne '0E0') { # only proceed if the update was a success
637 # If the patron changes to a category with enrollment fee, we add a fee
638 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
639 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
640 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
644 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
645 # cronjob will use for syncing with NL
646 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
647 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
648 'synctype' => 'norwegianpatrondb',
649 'borrowernumber' => $data{'borrowernumber'}
651 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
652 # we can sync as changed. And the "new sync" will pick up all changes since
653 # the patron was created anyway.
654 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
655 $borrowersync->update( { 'syncstatus' => 'edited' } );
657 # Set the value of 'sync'
658 $borrowersync->update( { 'sync' => $data{'sync'} } );
659 # Try to do the live sync
660 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
663 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
665 return $execute_success;
668 =head2 AddMember
670 $borrowernumber = &AddMember(%borrower);
672 insert new borrower into table
674 (%borrower keys are database columns. Database columns could be
675 different in different versions. Please look into database for correct
676 column names.)
678 Returns the borrowernumber upon success
680 Returns as undef upon any db error without further processing
682 =cut
685 sub AddMember {
686 my (%data) = @_;
687 my $dbh = C4::Context->dbh;
688 my $schema = Koha::Database->new()->schema;
690 # generate a proper login if none provided
691 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
692 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
694 # add expiration date if it isn't already there
695 unless ( $data{'dateexpiry'} ) {
696 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
699 # add enrollment date if it isn't already there
700 unless ( $data{'dateenrolled'} ) {
701 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
704 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
705 $data{'privacy'} =
706 $patron_category->default_privacy() eq 'default' ? 1
707 : $patron_category->default_privacy() eq 'never' ? 2
708 : $patron_category->default_privacy() eq 'forever' ? 0
709 : undef;
711 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
713 # Make a copy of the plain text password for later use
714 my $plain_text_password = $data{'password'};
716 # create a disabled account if no password provided
717 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
719 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
720 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
721 $data{'debarred'} = undef if ( not $data{'debarred'} );
722 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
724 # get only the columns of Borrower
725 my @columns = $schema->source('Borrower')->columns;
726 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
727 $new_member->{checkprevcheckout} ||= 'inherit';
728 delete $new_member->{borrowernumber};
730 my $rs = $schema->resultset('Borrower');
731 $data{borrowernumber} = $rs->create($new_member)->id;
733 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
734 # cronjob will use for syncing with NL
735 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
736 Koha::Database->new->schema->resultset('BorrowerSync')->create({
737 'borrowernumber' => $data{'borrowernumber'},
738 'synctype' => 'norwegianpatrondb',
739 'sync' => 1,
740 'syncstatus' => 'new',
741 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
745 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
746 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
748 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
750 return $data{borrowernumber};
753 =head2 Check_Userid
755 my $uniqueness = Check_Userid($userid,$borrowernumber);
757 $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 != '').
759 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.
761 return :
762 0 for not unique (i.e. this $userid already exists)
763 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
765 =cut
767 sub Check_Userid {
768 my ( $uid, $borrowernumber ) = @_;
770 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
772 return 0 if ( $uid eq C4::Context->config('user') );
774 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
776 my $params;
777 $params->{userid} = $uid;
778 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
780 my $count = $rs->count( $params );
782 return $count ? 0 : 1;
785 =head2 Generate_Userid
787 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
789 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
791 $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.
793 return :
794 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).
796 =cut
798 sub Generate_Userid {
799 my ($borrowernumber, $firstname, $surname) = @_;
800 my $newuid;
801 my $offset = 0;
802 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
803 do {
804 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
805 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
806 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
807 $newuid = unac_string('utf-8',$newuid);
808 $newuid .= $offset unless $offset == 0;
809 $offset++;
811 } while (!Check_Userid($newuid,$borrowernumber));
813 return $newuid;
816 sub changepassword {
817 my ( $uid, $member, $digest ) = @_;
818 my $dbh = C4::Context->dbh;
820 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
821 #Then we need to tell the user and have them create a new one.
822 my $resultcode;
823 my $sth =
824 $dbh->prepare(
825 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
826 $sth->execute( $uid, $member );
827 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
828 $resultcode=0;
830 else {
831 #Everything is good so we can update the information.
832 $sth =
833 $dbh->prepare(
834 "update borrowers set userid=?, password=? where borrowernumber=?");
835 $sth->execute( $uid, $digest, $member );
836 $resultcode=1;
839 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
840 return $resultcode;
845 =head2 fixup_cardnumber
847 Warning: The caller is responsible for locking the members table in write
848 mode, to avoid database corruption.
850 =cut
852 use vars qw( @weightings );
853 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
855 sub fixup_cardnumber {
856 my ($cardnumber) = @_;
857 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
859 # Find out whether member numbers should be generated
860 # automatically. Should be either "1" or something else.
861 # Defaults to "0", which is interpreted as "no".
863 # if ($cardnumber !~ /\S/ && $autonumber_members) {
864 ($autonumber_members) or return $cardnumber;
865 my $checkdigit = C4::Context->preference('checkdigit');
866 my $dbh = C4::Context->dbh;
867 if ( $checkdigit and $checkdigit eq 'katipo' ) {
869 # if checkdigit is selected, calculate katipo-style cardnumber.
870 # otherwise, just use the max()
871 # purpose: generate checksum'd member numbers.
872 # We'll assume we just got the max value of digits 2-8 of member #'s
873 # from the database and our job is to increment that by one,
874 # determine the 1st and 9th digits and return the full string.
875 my $sth = $dbh->prepare(
876 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
878 $sth->execute;
879 my $data = $sth->fetchrow_hashref;
880 $cardnumber = $data->{new_num};
881 if ( !$cardnumber ) { # If DB has no values,
882 $cardnumber = 1000000; # start at 1000000
883 } else {
884 $cardnumber += 1;
887 my $sum = 0;
888 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
889 # read weightings, left to right, 1 char at a time
890 my $temp1 = $weightings[$i];
892 # sequence left to right, 1 char at a time
893 my $temp2 = substr( $cardnumber, $i, 1 );
895 # mult each char 1-7 by its corresponding weighting
896 $sum += $temp1 * $temp2;
899 my $rem = ( $sum % 11 );
900 $rem = 'X' if $rem == 10;
902 return "V$cardnumber$rem";
903 } else {
905 my $sth = $dbh->prepare(
906 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
908 $sth->execute;
909 my ($result) = $sth->fetchrow;
910 return $result + 1;
912 return $cardnumber; # just here as a fallback/reminder
915 =head2 GetPendingIssues
917 my $issues = &GetPendingIssues(@borrowernumber);
919 Looks up what the patron with the given borrowernumber has borrowed.
921 C<&GetPendingIssues> returns a
922 reference-to-array where each element is a reference-to-hash; the
923 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
924 The keys include C<biblioitems> fields except marc and marcxml.
926 =cut
928 sub GetPendingIssues {
929 my @borrowernumbers = @_;
931 unless (@borrowernumbers ) { # return a ref_to_array
932 return \@borrowernumbers; # to not cause surprise to caller
935 # Borrowers part of the query
936 my $bquery = '';
937 for (my $i = 0; $i < @borrowernumbers; $i++) {
938 $bquery .= ' issues.borrowernumber = ?';
939 if ($i < $#borrowernumbers ) {
940 $bquery .= ' OR';
944 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
945 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
946 # FIXME: circ/ciculation.pl tries to sort by timestamp!
947 # FIXME: namespace collision: other collisions possible.
948 # FIXME: most of this data isn't really being used by callers.
949 my $query =
950 "SELECT issues.*,
951 items.*,
952 biblio.*,
953 biblioitems.volume,
954 biblioitems.number,
955 biblioitems.itemtype,
956 biblioitems.isbn,
957 biblioitems.issn,
958 biblioitems.publicationyear,
959 biblioitems.publishercode,
960 biblioitems.volumedate,
961 biblioitems.volumedesc,
962 biblioitems.lccn,
963 biblioitems.url,
964 borrowers.firstname,
965 borrowers.surname,
966 borrowers.cardnumber,
967 issues.timestamp AS timestamp,
968 issues.renewals AS renewals,
969 issues.borrowernumber AS borrowernumber,
970 items.renewals AS totalrenewals
971 FROM issues
972 LEFT JOIN items ON items.itemnumber = issues.itemnumber
973 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
974 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
975 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
976 WHERE
977 $bquery
978 ORDER BY issues.issuedate"
981 my $sth = C4::Context->dbh->prepare($query);
982 $sth->execute(@borrowernumbers);
983 my $data = $sth->fetchall_arrayref({});
984 my $today = dt_from_string;
985 foreach (@{$data}) {
986 if ($_->{issuedate}) {
987 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
989 $_->{date_due_sql} = $_->{date_due};
990 # FIXME no need to have this value
991 $_->{date_due} or next;
992 $_->{date_due_sql} = $_->{date_due};
993 # FIXME no need to have this value
994 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
995 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
996 $_->{overdue} = 1;
999 return $data;
1002 =head2 GetAllIssues
1004 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1006 Looks up what the patron with the given borrowernumber has borrowed,
1007 and sorts the results.
1009 C<$sortkey> is the name of a field on which to sort the results. This
1010 should be the name of a field in the C<issues>, C<biblio>,
1011 C<biblioitems>, or C<items> table in the Koha database.
1013 C<$limit> is the maximum number of results to return.
1015 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1016 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1017 C<items> tables of the Koha database.
1019 =cut
1022 sub GetAllIssues {
1023 my ( $borrowernumber, $order, $limit ) = @_;
1025 return unless $borrowernumber;
1026 $order = 'date_due desc' unless $order;
1028 my $dbh = C4::Context->dbh;
1029 my $query =
1030 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1031 FROM issues
1032 LEFT JOIN items on items.itemnumber=issues.itemnumber
1033 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1034 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1035 WHERE borrowernumber=?
1036 UNION ALL
1037 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1038 FROM old_issues
1039 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1040 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1041 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1042 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1043 order by ' . $order;
1044 if ($limit) {
1045 $query .= " limit $limit";
1048 my $sth = $dbh->prepare($query);
1049 $sth->execute( $borrowernumber, $borrowernumber );
1050 return $sth->fetchall_arrayref( {} );
1054 =head2 GetMemberAccountRecords
1056 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1058 Looks up accounting data for the patron with the given borrowernumber.
1060 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1061 reference-to-array, where each element is a reference-to-hash; the
1062 keys are the fields of the C<accountlines> table in the Koha database.
1063 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1064 total amount outstanding for all of the account lines.
1066 =cut
1068 sub GetMemberAccountRecords {
1069 my ($borrowernumber) = @_;
1070 my $dbh = C4::Context->dbh;
1071 my @acctlines;
1072 my $numlines = 0;
1073 my $strsth = qq(
1074 SELECT *
1075 FROM accountlines
1076 WHERE borrowernumber=?);
1077 $strsth.=" ORDER BY accountlines_id desc";
1078 my $sth= $dbh->prepare( $strsth );
1079 $sth->execute( $borrowernumber );
1081 my $total = 0;
1082 while ( my $data = $sth->fetchrow_hashref ) {
1083 if ( $data->{itemnumber} ) {
1084 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1085 $data->{biblionumber} = $biblio->{biblionumber};
1086 $data->{title} = $biblio->{title};
1088 $acctlines[$numlines] = $data;
1089 $numlines++;
1090 $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1092 $total /= 1000;
1093 return ( $total, \@acctlines,$numlines);
1096 =head2 GetMemberAccountBalance
1098 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1100 Calculates amount immediately owing by the patron - non-issue charges.
1101 Based on GetMemberAccountRecords.
1102 Charges exempt from non-issue are:
1103 * Res (reserves)
1104 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1105 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1107 =cut
1109 sub GetMemberAccountBalance {
1110 my ($borrowernumber) = @_;
1112 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1114 my @not_fines;
1115 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1116 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1117 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1118 my $dbh = C4::Context->dbh;
1119 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1120 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1122 my %not_fine = map {$_ => 1} @not_fines;
1124 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1125 my $other_charges = 0;
1126 foreach (@$acctlines) {
1127 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1130 return ( $total, $total - $other_charges, $other_charges);
1133 =head2 GetBorNotifyAcctRecord
1135 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1137 Looks up accounting data for the patron with the given borrowernumber per file number.
1139 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1140 reference-to-array, where each element is a reference-to-hash; the
1141 keys are the fields of the C<accountlines> table in the Koha database.
1142 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1143 total amount outstanding for all of the account lines.
1145 =cut
1147 sub GetBorNotifyAcctRecord {
1148 my ( $borrowernumber, $notifyid ) = @_;
1149 my $dbh = C4::Context->dbh;
1150 my @acctlines;
1151 my $numlines = 0;
1152 my $sth = $dbh->prepare(
1153 "SELECT *
1154 FROM accountlines
1155 WHERE borrowernumber=?
1156 AND notify_id=?
1157 AND amountoutstanding != '0'
1158 ORDER BY notify_id,accounttype
1161 $sth->execute( $borrowernumber, $notifyid );
1162 my $total = 0;
1163 while ( my $data = $sth->fetchrow_hashref ) {
1164 if ( $data->{itemnumber} ) {
1165 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1166 $data->{biblionumber} = $biblio->{biblionumber};
1167 $data->{title} = $biblio->{title};
1169 $acctlines[$numlines] = $data;
1170 $numlines++;
1171 $total += int(100 * $data->{'amountoutstanding'});
1173 $total /= 100;
1174 return ( $total, \@acctlines, $numlines );
1177 =head2 checkuniquemember (OUEST-PROVENCE)
1179 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1181 Checks that a member exists or not in the database.
1183 C<&result> is nonzero (=exist) or 0 (=does not exist)
1184 C<&categorycode> is from categorycode table
1185 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1186 C<&surname> is the surname
1187 C<&firstname> is the firstname (only if collectivity=0)
1188 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1190 =cut
1192 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1193 # This is especially true since first name is not even a required field.
1195 sub checkuniquemember {
1196 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1197 my $dbh = C4::Context->dbh;
1198 my $request = ($collectivity) ?
1199 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1200 ($dateofbirth) ?
1201 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1202 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1203 my $sth = $dbh->prepare($request);
1204 if ($collectivity) {
1205 $sth->execute( uc($surname) );
1206 } elsif($dateofbirth){
1207 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1208 }else{
1209 $sth->execute( uc($surname), ucfirst($firstname));
1211 my @data = $sth->fetchrow;
1212 ( $data[0] ) and return $data[0], $data[1];
1213 return 0;
1216 sub checkcardnumber {
1217 my ( $cardnumber, $borrowernumber ) = @_;
1219 # If cardnumber is null, we assume they're allowed.
1220 return 0 unless defined $cardnumber;
1222 my $dbh = C4::Context->dbh;
1223 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1224 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1225 my $sth = $dbh->prepare($query);
1226 $sth->execute(
1227 $cardnumber,
1228 ( $borrowernumber ? $borrowernumber : () )
1231 return 1 if $sth->fetchrow_hashref;
1233 my ( $min_length, $max_length ) = get_cardnumber_length();
1234 return 2
1235 if length $cardnumber > $max_length
1236 or length $cardnumber < $min_length;
1238 return 0;
1241 =head2 get_cardnumber_length
1243 my ($min, $max) = C4::Members::get_cardnumber_length()
1245 Returns the minimum and maximum length for patron cardnumbers as
1246 determined by the CardnumberLength system preference, the
1247 BorrowerMandatoryField system preference, and the width of the
1248 database column.
1250 =cut
1252 sub get_cardnumber_length {
1253 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1254 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1255 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1256 # Is integer and length match
1257 if ( $cardnumber_length =~ m|^\d+$| ) {
1258 $min = $max = $cardnumber_length
1259 if $cardnumber_length >= $min
1260 and $cardnumber_length <= $max;
1262 # Else assuming it is a range
1263 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1264 $min = $1 if $1 and $min < $1;
1265 $max = $2 if $2 and $max > $2;
1269 return ( $min, $max );
1272 =head2 GetFirstValidEmailAddress
1274 $email = GetFirstValidEmailAddress($borrowernumber);
1276 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1277 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1278 addresses.
1280 =cut
1282 sub GetFirstValidEmailAddress {
1283 my $borrowernumber = shift;
1284 my $dbh = C4::Context->dbh;
1285 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1286 $sth->execute( $borrowernumber );
1287 my $data = $sth->fetchrow_hashref;
1289 if ($data->{'email'}) {
1290 return $data->{'email'};
1291 } elsif ($data->{'emailpro'}) {
1292 return $data->{'emailpro'};
1293 } elsif ($data->{'B_email'}) {
1294 return $data->{'B_email'};
1295 } else {
1296 return '';
1300 =head2 GetNoticeEmailAddress
1302 $email = GetNoticeEmailAddress($borrowernumber);
1304 Return the email address of borrower used for notices, given the borrowernumber.
1305 Returns the empty string if no email address.
1307 =cut
1309 sub GetNoticeEmailAddress {
1310 my $borrowernumber = shift;
1312 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1313 # if syspref is set to 'first valid' (value == OFF), look up email address
1314 if ( $which_address eq 'OFF' ) {
1315 return GetFirstValidEmailAddress($borrowernumber);
1317 # specified email address field
1318 my $dbh = C4::Context->dbh;
1319 my $sth = $dbh->prepare( qq{
1320 SELECT $which_address AS primaryemail
1321 FROM borrowers
1322 WHERE borrowernumber=?
1323 } );
1324 $sth->execute($borrowernumber);
1325 my $data = $sth->fetchrow_hashref;
1326 return $data->{'primaryemail'} || '';
1329 =head2 GetExpiryDate
1331 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1333 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1334 Return date is also in ISO format.
1336 =cut
1338 sub GetExpiryDate {
1339 my ( $categorycode, $dateenrolled ) = @_;
1340 my $enrolments;
1341 if ($categorycode) {
1342 my $dbh = C4::Context->dbh;
1343 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1344 $sth->execute($categorycode);
1345 $enrolments = $sth->fetchrow_hashref;
1347 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1348 my @date = split (/-/,$dateenrolled);
1349 if($enrolments->{enrolmentperiod}){
1350 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1351 }else{
1352 return $enrolments->{enrolmentperioddate};
1356 =head2 GetUpcomingMembershipExpires
1358 my $expires = GetUpcomingMembershipExpires({
1359 branch => $branch, before => $before, after => $after,
1362 $branch is an optional branch code.
1363 $before/$after is an optional number of days before/after the date that
1364 is set by the preference MembershipExpiryDaysNotice.
1365 If the pref would be 14, before 2 and after 3, you will get all expires
1366 from 12 to 17 days.
1368 =cut
1370 sub GetUpcomingMembershipExpires {
1371 my ( $params ) = @_;
1372 my $before = $params->{before} || 0;
1373 my $after = $params->{after} || 0;
1374 my $branch = $params->{branch};
1376 my $dbh = C4::Context->dbh;
1377 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1378 my $date1 = dt_from_string->add( days => $days - $before );
1379 my $date2 = dt_from_string->add( days => $days + $after );
1380 $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1381 $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1383 my $query = q|
1384 SELECT borrowers.*, categories.description,
1385 branches.branchname, branches.branchemail FROM borrowers
1386 LEFT JOIN branches USING (branchcode)
1387 LEFT JOIN categories USING (categorycode)
1389 if( $branch ) {
1390 $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1391 } else {
1392 $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1395 my $sth = $dbh->prepare( $query );
1396 my @pars = $branch? ( $branch ): ();
1397 push @pars, $date1, $date2;
1398 $sth->execute( @pars );
1399 my $results = $sth->fetchall_arrayref( {} );
1400 return $results;
1403 =head2 GetborCatFromCatType
1405 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1407 Looks up the different types of borrowers in the database. Returns two
1408 elements: a reference-to-array, which lists the borrower category
1409 codes, and a reference-to-hash, which maps the borrower category codes
1410 to category descriptions.
1412 =cut
1415 sub GetborCatFromCatType {
1416 my ( $category_type, $action, $no_branch_limit ) = @_;
1418 my $branch_limit = $no_branch_limit
1420 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1422 # FIXME - This API seems both limited and dangerous.
1423 my $dbh = C4::Context->dbh;
1425 my $request = qq{
1426 SELECT DISTINCT categories.categorycode, categories.description
1427 FROM categories
1429 $request .= qq{
1430 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1431 } if $branch_limit;
1432 if($action) {
1433 $request .= " $action ";
1434 $request .= " AND (branchcode = ? OR branchcode IS NULL)" if $branch_limit;
1435 } else {
1436 $request .= " WHERE branchcode = ? OR branchcode IS NULL" if $branch_limit;
1438 $request .= " ORDER BY categorycode";
1440 my $sth = $dbh->prepare($request);
1441 $sth->execute(
1442 $action ? $category_type : (),
1443 $branch_limit ? $branch_limit : ()
1446 my %labels;
1447 my @codes;
1449 while ( my $data = $sth->fetchrow_hashref ) {
1450 push @codes, $data->{'categorycode'};
1451 $labels{ $data->{'categorycode'} } = $data->{'description'};
1453 $sth->finish;
1454 return ( \@codes, \%labels );
1457 =head2 GetBorrowercategory
1459 $hashref = &GetBorrowercategory($categorycode);
1461 Given the borrower's category code, the function returns the corresponding
1462 data hashref for a comprehensive information display.
1464 =cut
1466 sub GetBorrowercategory {
1467 my ($catcode) = @_;
1468 my $dbh = C4::Context->dbh;
1469 if ($catcode){
1470 my $sth =
1471 $dbh->prepare(
1472 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1473 FROM categories
1474 WHERE categorycode = ?"
1476 $sth->execute($catcode);
1477 my $data =
1478 $sth->fetchrow_hashref;
1479 return $data;
1481 return;
1482 } # sub getborrowercategory
1485 =head2 GetBorrowerCategorycode
1487 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1489 Given the borrowernumber, the function returns the corresponding categorycode
1491 =cut
1493 sub GetBorrowerCategorycode {
1494 my ( $borrowernumber ) = @_;
1495 my $dbh = C4::Context->dbh;
1496 my $sth = $dbh->prepare( qq{
1497 SELECT categorycode
1498 FROM borrowers
1499 WHERE borrowernumber = ?
1500 } );
1501 $sth->execute( $borrowernumber );
1502 return $sth->fetchrow;
1505 =head2 GetBorrowercategoryList
1507 $arrayref_hashref = &GetBorrowercategoryList;
1508 If no category code provided, the function returns all the categories.
1510 =cut
1512 sub GetBorrowercategoryList {
1513 my $no_branch_limit = @_ ? shift : 0;
1514 my $branch_limit = $no_branch_limit
1516 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1517 my $dbh = C4::Context->dbh;
1518 my $query = "SELECT categories.* FROM categories";
1519 $query .= qq{
1520 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1521 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1522 } if $branch_limit;
1523 $query .= " ORDER BY description";
1524 my $sth = $dbh->prepare( $query );
1525 $sth->execute( $branch_limit ? $branch_limit : () );
1526 my $data = $sth->fetchall_arrayref( {} );
1527 $sth->finish;
1528 return $data;
1529 } # sub getborrowercategory
1531 =head2 GetAge
1533 $dateofbirth,$date = &GetAge($date);
1535 this function return the borrowers age with the value of dateofbirth
1537 =cut
1540 sub GetAge{
1541 my ( $date, $date_ref ) = @_;
1543 if ( not defined $date_ref ) {
1544 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1547 my ( $year1, $month1, $day1 ) = split /-/, $date;
1548 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1550 my $age = $year2 - $year1;
1551 if ( $month1 . $day1 > $month2 . $day2 ) {
1552 $age--;
1555 return $age;
1556 } # sub get_age
1558 =head2 SetAge
1560 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1561 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1562 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1564 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1565 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1567 This function sets the borrower's dateofbirth to match the given age.
1568 Optionally relative to the given $datetime_reference.
1570 @PARAM1 koha.borrowers-object
1571 @PARAM2 DateTime::Duration-object as the desired age
1572 OR a ISO 8601 Date. (To make the API more pleasant)
1573 @PARAM3 DateTime-object as the relative date, defaults to now().
1574 RETURNS The given borrower reference @PARAM1.
1575 DIES If there was an error with the ISO Date handling.
1577 =cut
1580 sub SetAge{
1581 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1582 $datetime_ref = DateTime->now() unless $datetime_ref;
1584 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1585 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1586 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1588 else {
1589 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1593 my $new_datetime_ref = $datetime_ref->clone();
1594 $new_datetime_ref->subtract_duration( $datetimeduration );
1596 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1598 return $borrower;
1599 } # sub SetAge
1601 =head2 GetSortDetails (OUEST-PROVENCE)
1603 ($lib) = &GetSortDetails($category,$sortvalue);
1605 Returns the authorized value details
1606 C<&$lib>return value of authorized value details
1607 C<&$sortvalue>this is the value of authorized value
1608 C<&$category>this is the value of authorized value category
1610 =cut
1612 sub GetSortDetails {
1613 my ( $category, $sortvalue ) = @_;
1614 my $dbh = C4::Context->dbh;
1615 my $query = qq|SELECT lib
1616 FROM authorised_values
1617 WHERE category=?
1618 AND authorised_value=? |;
1619 my $sth = $dbh->prepare($query);
1620 $sth->execute( $category, $sortvalue );
1621 my $lib = $sth->fetchrow;
1622 return ($lib) if ($lib);
1623 return ($sortvalue) unless ($lib);
1626 =head2 MoveMemberToDeleted
1628 $result = &MoveMemberToDeleted($borrowernumber);
1630 Copy the record from borrowers to deletedborrowers table.
1631 The routine returns 1 for success, undef for failure.
1633 =cut
1635 sub MoveMemberToDeleted {
1636 my ($member) = shift or return;
1638 my $schema = Koha::Database->new()->schema();
1639 my $borrowers_rs = $schema->resultset('Borrower');
1640 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1641 my $borrower = $borrowers_rs->find($member);
1642 return unless $borrower;
1644 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1646 return $deleted ? 1 : undef;
1649 =head2 DelMember
1651 DelMember($borrowernumber);
1653 This function remove directly a borrower whitout writing it on deleteborrower.
1654 + Deletes reserves for the borrower
1656 =cut
1658 sub DelMember {
1659 my $dbh = C4::Context->dbh;
1660 my $borrowernumber = shift;
1661 #warn "in delmember with $borrowernumber";
1662 return unless $borrowernumber; # borrowernumber is mandatory.
1663 # Delete Patron's holds
1664 my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1665 $_->delete for @holds;
1667 my $query = "
1668 DELETE
1669 FROM borrowers
1670 WHERE borrowernumber = ?
1672 my $sth = $dbh->prepare($query);
1673 $sth->execute($borrowernumber);
1674 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1675 return $sth->rows;
1678 =head2 HandleDelBorrower
1680 HandleDelBorrower($borrower);
1682 When a member is deleted (DelMember in Members.pm), you should call me first.
1683 This routine deletes/moves lists and entries for the deleted member/borrower.
1684 Lists owned by the borrower are deleted, but entries from the borrower to
1685 other lists are kept.
1687 =cut
1689 sub HandleDelBorrower {
1690 my ($borrower)= @_;
1691 my $query;
1692 my $dbh = C4::Context->dbh;
1694 #Delete all lists and all shares of this borrower
1695 #Consistent with the approach Koha uses on deleting individual lists
1696 #Note that entries in virtualshelfcontents added by this borrower to
1697 #lists of others will be handled by a table constraint: the borrower
1698 #is set to NULL in those entries.
1699 $query="DELETE FROM virtualshelves WHERE owner=?";
1700 $dbh->do($query,undef,($borrower));
1702 #NOTE:
1703 #We could handle the above deletes via a constraint too.
1704 #But a new BZ report 11889 has been opened to discuss another approach.
1705 #Instead of deleting we could also disown lists (based on a pref).
1706 #In that way we could save shared and public lists.
1707 #The current table constraints support that idea now.
1708 #This pref should then govern the results of other routines/methods such as
1709 #Koha::Virtualshelf->new->delete too.
1712 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1714 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1716 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1717 Returns ISO date.
1719 =cut
1721 sub ExtendMemberSubscriptionTo {
1722 my ( $borrowerid,$date) = @_;
1723 my $dbh = C4::Context->dbh;
1724 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1725 unless ($date){
1726 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1727 eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'} ), dateonly => 1, dateformat => 'iso' } ); }
1729 output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1730 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1732 my $sth = $dbh->do(<<EOF);
1733 UPDATE borrowers
1734 SET dateexpiry='$date'
1735 WHERE borrowernumber='$borrowerid'
1738 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1740 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1741 return $date if ($sth);
1742 return 0;
1745 =head2 GetHideLostItemsPreference
1747 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1749 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1750 C<&$hidelostitemspref>return value of function, 0 or 1
1752 =cut
1754 sub GetHideLostItemsPreference {
1755 my ($borrowernumber) = @_;
1756 my $dbh = C4::Context->dbh;
1757 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1758 my $sth = $dbh->prepare($query);
1759 $sth->execute($borrowernumber);
1760 my $hidelostitems = $sth->fetchrow;
1761 return $hidelostitems;
1764 =head2 GetBorrowersToExpunge
1766 $borrowers = &GetBorrowersToExpunge(
1767 not_borrowed_since => $not_borrowed_since,
1768 expired_before => $expired_before,
1769 category_code => $category_code,
1770 patron_list_id => $patron_list_id,
1771 branchcode => $branchcode
1774 This function get all borrowers based on the given criteria.
1776 =cut
1778 sub GetBorrowersToExpunge {
1780 my $params = shift;
1781 my $filterdate = $params->{'not_borrowed_since'};
1782 my $filterexpiry = $params->{'expired_before'};
1783 my $filtercategory = $params->{'category_code'};
1784 my $filterbranch = $params->{'branchcode'} ||
1785 ((C4::Context->preference('IndependentBranches')
1786 && C4::Context->userenv
1787 && !C4::Context->IsSuperLibrarian()
1788 && C4::Context->userenv->{branch})
1789 ? C4::Context->userenv->{branch}
1790 : "");
1791 my $filterpatronlist = $params->{'patron_list_id'};
1793 my $dbh = C4::Context->dbh;
1794 my $query = q|
1795 SELECT borrowers.borrowernumber,
1796 MAX(old_issues.timestamp) AS latestissue,
1797 MAX(issues.timestamp) AS currentissue
1798 FROM borrowers
1799 JOIN categories USING (categorycode)
1800 LEFT JOIN (
1801 SELECT guarantorid
1802 FROM borrowers
1803 WHERE guarantorid IS NOT NULL
1804 AND guarantorid <> 0
1805 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1806 LEFT JOIN old_issues USING (borrowernumber)
1807 LEFT JOIN issues USING (borrowernumber)|;
1808 if ( $filterpatronlist ){
1809 $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1811 $query .= q| WHERE category_type <> 'S'
1812 AND tmp.guarantorid IS NULL
1814 my @query_params;
1815 if ( $filterbranch && $filterbranch ne "" ) {
1816 $query.= " AND borrowers.branchcode = ? ";
1817 push( @query_params, $filterbranch );
1819 if ( $filterexpiry ) {
1820 $query .= " AND dateexpiry < ? ";
1821 push( @query_params, $filterexpiry );
1823 if ( $filtercategory ) {
1824 $query .= " AND categorycode = ? ";
1825 push( @query_params, $filtercategory );
1827 if ( $filterpatronlist ){
1828 $query.=" AND patron_list_id = ? ";
1829 push( @query_params, $filterpatronlist );
1831 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1832 if ( $filterdate ) {
1833 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1834 push @query_params,$filterdate;
1836 warn $query if $debug;
1838 my $sth = $dbh->prepare($query);
1839 if (scalar(@query_params)>0){
1840 $sth->execute(@query_params);
1842 else {
1843 $sth->execute;
1846 my @results;
1847 while ( my $data = $sth->fetchrow_hashref ) {
1848 push @results, $data;
1850 return \@results;
1853 =head2 GetBorrowersWhoHaveNeverBorrowed
1855 $results = &GetBorrowersWhoHaveNeverBorrowed
1857 This function get all borrowers who have never borrowed.
1859 I<$result> is a ref to an array which all elements are a hasref.
1861 =cut
1863 sub GetBorrowersWhoHaveNeverBorrowed {
1864 my $filterbranch = shift ||
1865 ((C4::Context->preference('IndependentBranches')
1866 && C4::Context->userenv
1867 && !C4::Context->IsSuperLibrarian()
1868 && C4::Context->userenv->{branch})
1869 ? C4::Context->userenv->{branch}
1870 : "");
1871 my $dbh = C4::Context->dbh;
1872 my $query = "
1873 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1874 FROM borrowers
1875 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1876 WHERE issues.borrowernumber IS NULL
1878 my @query_params;
1879 if ($filterbranch && $filterbranch ne ""){
1880 $query.=" AND borrowers.branchcode= ?";
1881 push @query_params,$filterbranch;
1883 warn $query if $debug;
1885 my $sth = $dbh->prepare($query);
1886 if (scalar(@query_params)>0){
1887 $sth->execute(@query_params);
1889 else {
1890 $sth->execute;
1893 my @results;
1894 while ( my $data = $sth->fetchrow_hashref ) {
1895 push @results, $data;
1897 return \@results;
1900 =head2 GetBorrowersWithIssuesHistoryOlderThan
1902 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1904 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1906 I<$result> is a ref to an array which all elements are a hashref.
1907 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1909 =cut
1911 sub GetBorrowersWithIssuesHistoryOlderThan {
1912 my $dbh = C4::Context->dbh;
1913 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1914 my $filterbranch = shift ||
1915 ((C4::Context->preference('IndependentBranches')
1916 && C4::Context->userenv
1917 && !C4::Context->IsSuperLibrarian()
1918 && C4::Context->userenv->{branch})
1919 ? C4::Context->userenv->{branch}
1920 : "");
1921 my $query = "
1922 SELECT count(borrowernumber) as n,borrowernumber
1923 FROM old_issues
1924 WHERE returndate < ?
1925 AND borrowernumber IS NOT NULL
1927 my @query_params;
1928 push @query_params, $date;
1929 if ($filterbranch){
1930 $query.=" AND branchcode = ?";
1931 push @query_params, $filterbranch;
1933 $query.=" GROUP BY borrowernumber ";
1934 warn $query if $debug;
1935 my $sth = $dbh->prepare($query);
1936 $sth->execute(@query_params);
1937 my @results;
1939 while ( my $data = $sth->fetchrow_hashref ) {
1940 push @results, $data;
1942 return \@results;
1945 =head2 GetBorrowersNamesAndLatestIssue
1947 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1949 this function get borrowers Names and surnames and Issue information.
1951 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1952 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1954 =cut
1956 sub GetBorrowersNamesAndLatestIssue {
1957 my $dbh = C4::Context->dbh;
1958 my @borrowernumbers=@_;
1959 my $query = "
1960 SELECT surname,lastname, phone, email,max(timestamp)
1961 FROM borrowers
1962 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1963 GROUP BY borrowernumber
1965 my $sth = $dbh->prepare($query);
1966 $sth->execute;
1967 my $results = $sth->fetchall_arrayref({});
1968 return $results;
1971 =head2 IssueSlip
1973 IssueSlip($branchcode, $borrowernumber, $quickslip)
1975 Returns letter hash ( see C4::Letters::GetPreparedLetter )
1977 $quickslip is boolean, to indicate whether we want a quick slip
1979 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1981 Both slips:
1983 <<branches.*>>
1984 <<borrowers.*>>
1986 ISSUESLIP:
1988 <checkedout>
1989 <<biblio.*>>
1990 <<items.*>>
1991 <<biblioitems.*>>
1992 <<issues.*>>
1993 </checkedout>
1995 <overdue>
1996 <<biblio.*>>
1997 <<items.*>>
1998 <<biblioitems.*>>
1999 <<issues.*>>
2000 </overdue>
2002 <news>
2003 <<opac_news.*>>
2004 </news>
2006 ISSUEQSLIP:
2008 <checkedout>
2009 <<biblio.*>>
2010 <<items.*>>
2011 <<biblioitems.*>>
2012 <<issues.*>>
2013 </checkedout>
2015 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2017 =cut
2019 sub IssueSlip {
2020 my ($branch, $borrowernumber, $quickslip) = @_;
2022 # FIXME Check callers before removing this statement
2023 #return unless $borrowernumber;
2025 my @issues = @{ GetPendingIssues($borrowernumber) };
2027 for my $issue (@issues) {
2028 $issue->{date_due} = $issue->{date_due_sql};
2029 if ($quickslip) {
2030 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2031 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2032 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2033 $issue->{now} = 1;
2038 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2039 @issues = sort {
2040 my $s = $b->{timestamp} <=> $a->{timestamp};
2041 $s == 0 ?
2042 $b->{issuedate} <=> $a->{issuedate} : $s;
2043 } @issues;
2045 my ($letter_code, %repeat);
2046 if ( $quickslip ) {
2047 $letter_code = 'ISSUEQSLIP';
2048 %repeat = (
2049 'checkedout' => [ map {
2050 'biblio' => $_,
2051 'items' => $_,
2052 'biblioitems' => $_,
2053 'issues' => $_,
2054 }, grep { $_->{'now'} } @issues ],
2057 else {
2058 $letter_code = 'ISSUESLIP';
2059 %repeat = (
2060 'checkedout' => [ map {
2061 'biblio' => $_,
2062 'items' => $_,
2063 'biblioitems' => $_,
2064 'issues' => $_,
2065 }, grep { !$_->{'overdue'} } @issues ],
2067 'overdue' => [ map {
2068 'biblio' => $_,
2069 'items' => $_,
2070 'biblioitems' => $_,
2071 'issues' => $_,
2072 }, grep { $_->{'overdue'} } @issues ],
2074 'news' => [ map {
2075 $_->{'timestamp'} = $_->{'newdate'};
2076 { opac_news => $_ }
2077 } @{ GetNewsToDisplay("slip",$branch) } ],
2081 return C4::Letters::GetPreparedLetter (
2082 module => 'circulation',
2083 letter_code => $letter_code,
2084 branchcode => $branch,
2085 tables => {
2086 'branches' => $branch,
2087 'borrowers' => $borrowernumber,
2089 repeat => \%repeat,
2093 =head2 GetBorrowersWithEmail
2095 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2097 This gets a list of users and their basic details from their email address.
2098 As it's possible for multiple user to have the same email address, it provides
2099 you with all of them. If there is no userid for the user, there will be an
2100 C<undef> there. An empty list will be returned if there are no matches.
2102 =cut
2104 sub GetBorrowersWithEmail {
2105 my $email = shift;
2107 my $dbh = C4::Context->dbh;
2109 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2110 my $sth=$dbh->prepare($query);
2111 $sth->execute($email);
2112 my @result = ();
2113 while (my $ref = $sth->fetch) {
2114 push @result, $ref;
2116 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2117 return @result;
2120 =head2 AddMember_Opac
2122 =cut
2124 sub AddMember_Opac {
2125 my ( %borrower ) = @_;
2127 $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2128 if (not defined $borrower{'password'}){
2129 my $sr = new String::Random;
2130 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2131 my $password = $sr->randpattern("AAAAAAAAAA");
2132 $borrower{'password'} = $password;
2135 $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
2137 my $borrowernumber = AddMember(%borrower);
2139 return ( $borrowernumber, $borrower{'password'} );
2142 =head2 AddEnrolmentFeeIfNeeded
2144 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2146 Add enrolment fee for a patron if needed.
2148 =cut
2150 sub AddEnrolmentFeeIfNeeded {
2151 my ( $categorycode, $borrowernumber ) = @_;
2152 # check for enrollment fee & add it if needed
2153 my $dbh = C4::Context->dbh;
2154 my $sth = $dbh->prepare(q{
2155 SELECT enrolmentfee
2156 FROM categories
2157 WHERE categorycode=?
2159 $sth->execute( $categorycode );
2160 if ( $sth->err ) {
2161 warn sprintf('Database returned the following error: %s', $sth->errstr);
2162 return;
2164 my ($enrolmentfee) = $sth->fetchrow;
2165 if ($enrolmentfee && $enrolmentfee > 0) {
2166 # insert fee in patron debts
2167 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2171 =head2 HasOverdues
2173 =cut
2175 sub HasOverdues {
2176 my ( $borrowernumber ) = @_;
2178 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2179 my $sth = C4::Context->dbh->prepare( $sql );
2180 $sth->execute( $borrowernumber );
2181 my ( $count ) = $sth->fetchrow_array();
2183 return $count;
2186 =head2 DeleteExpiredOpacRegistrations
2188 Delete accounts that haven't been upgraded from the 'temporary' category
2189 Returns the number of removed patrons
2191 =cut
2193 sub DeleteExpiredOpacRegistrations {
2195 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2196 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2198 return 0 if not $category_code or not defined $delay or $delay eq q||;
2200 my $query = qq|
2201 SELECT borrowernumber
2202 FROM borrowers
2203 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2205 my $dbh = C4::Context->dbh;
2206 my $sth = $dbh->prepare($query);
2207 $sth->execute( $category_code, $delay );
2208 my $cnt=0;
2209 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2210 DelMember($borrowernumber);
2211 $cnt++;
2213 return $cnt;
2216 =head2 DeleteUnverifiedOpacRegistrations
2218 Delete all unverified self registrations in borrower_modifications,
2219 older than the specified number of days.
2221 =cut
2223 sub DeleteUnverifiedOpacRegistrations {
2224 my ( $days ) = @_;
2225 my $dbh = C4::Context->dbh;
2226 my $sql=qq|
2227 DELETE FROM borrower_modifications
2228 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2229 my $cnt=$dbh->do($sql, undef, ($days) );
2230 return $cnt eq '0E0'? 0: $cnt;
2233 sub GetOverduesForPatron {
2234 my ( $borrowernumber ) = @_;
2236 my $sql = "
2237 SELECT *
2238 FROM issues, items, biblio, biblioitems
2239 WHERE items.itemnumber=issues.itemnumber
2240 AND biblio.biblionumber = items.biblionumber
2241 AND biblio.biblionumber = biblioitems.biblionumber
2242 AND issues.borrowernumber = ?
2243 AND date_due < NOW()
2246 my $sth = C4::Context->dbh->prepare( $sql );
2247 $sth->execute( $borrowernumber );
2249 return $sth->fetchall_arrayref({});
2252 END { } # module clean-up code here (global destructor)
2256 __END__
2258 =head1 AUTHOR
2260 Koha Team
2262 =cut