Bug 16909: Koha::Patrons - Remove checkuniquemember
[koha.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
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.
13 #
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.
18 #
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>.
21
22
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 Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
42 use Koha::Database;
43 use Koha::Holds;
44 use Koha::List::Patron;
45 use Koha::Patrons;
46
47 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
48
49 use Module::Load::Conditional qw( can_load );
50 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
51    $debug && warn "Unable to load Koha::NorwegianPatronDB";
52 }
53
54
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
64
65         &GetMemberIssuesAndFines
66         &GetPendingIssues
67         &GetAllIssues
68
69         &GetFirstValidEmailAddress
70         &GetNoticeEmailAddress
71
72         &GetAge
73         &GetSortDetails
74         &GetTitles
75
76         &GetHideLostItemsPreference
77
78         &IsMemberBlocked
79         &GetMemberAccountRecords
80         &GetBorNotifyAcctRecord
81
82         &GetborCatFromCatType
83         &GetBorrowercategory
84         GetBorrowerCategorycode
85         &GetBorrowercategoryList
86
87         &GetBorrowersToExpunge
88         &GetBorrowersWhoHaveNeverBorrowed
89         &GetBorrowersWithIssuesHistoryOlderThan
90
91         &GetExpiryDate
92         &GetUpcomingMembershipExpires
93
94         &IssueSlip
95         GetBorrowersWithEmail
96
97         HasOverdues
98         GetOverduesForPatron
99     );
100
101     #Modify data
102     push @EXPORT, qw(
103         &ModMember
104         &changepassword
105     );
106
107     #Delete data
108     push @EXPORT, qw(
109         &DelMember
110     );
111
112     #Insert data
113     push @EXPORT, qw(
114         &AddMember
115         &AddMember_Opac
116         &MoveMemberToDeleted
117         &ExtendMemberSubscriptionTo
118     );
119
120     #Check data
121     push @EXPORT, qw(
122         &checkuniquemember
123         &checkuserpassword
124         &Check_Userid
125         &Generate_Userid
126         &fixup_cardnumber
127         &checkcardnumber
128     );
129 }
130
131 =head1 NAME
132
133 C4::Members - Perl Module containing convenience functions for member handling
134
135 =head1 SYNOPSIS
136
137 use C4::Members;
138
139 =head1 DESCRIPTION
140
141 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
142
143 =head1 FUNCTIONS
144
145 =head2 GetMemberDetails
146
147 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
148
149 Looks up a patron and returns information about him or her. If
150 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
151 up the borrower by number; otherwise, it looks up the borrower by card
152 number.
153
154 C<$borrower> is a reference-to-hash whose keys are the fields of the
155 borrowers table in the Koha database. In addition,
156 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
157 about the patron. Its keys act as flags :
158
159     if $borrower->{flags}->{LOST} {
160         # Patron's card was reported lost
161     }
162
163 If the state of a flag means that the patron should not be
164 allowed to borrow any more books, then it will have a C<noissues> key
165 with a true value.
166
167 See patronflags for more details.
168
169 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
170 about the top-level permissions flags set for the borrower.  For example,
171 if a user has the "editcatalogue" permission,
172 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
173 the value "1".
174
175 =cut
176
177 sub GetMemberDetails {
178     my ( $borrowernumber, $cardnumber ) = @_;
179     my $dbh = C4::Context->dbh;
180     my $query;
181     my $sth;
182     if ($borrowernumber) {
183         $sth = $dbh->prepare("
184             SELECT borrowers.*,
185                    category_type,
186                    categories.description,
187                    categories.BlockExpiredPatronOpacActions,
188                    reservefee,
189                    enrolmentperiod
190             FROM borrowers
191             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
192             WHERE borrowernumber = ?
193         ");
194         $sth->execute($borrowernumber);
195     }
196     elsif ($cardnumber) {
197         $sth = $dbh->prepare("
198             SELECT borrowers.*,
199                    category_type,
200                    categories.description,
201                    categories.BlockExpiredPatronOpacActions,
202                    reservefee,
203                    enrolmentperiod
204             FROM borrowers
205             LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
206             WHERE cardnumber = ?
207         ");
208         $sth->execute($cardnumber);
209     }
210     else {
211         return;
212     }
213     my $borrower = $sth->fetchrow_hashref;
214     return unless $borrower;
215     my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
216     $borrower->{'amountoutstanding'} = $amount;
217     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
218     my $flags = patronflags( $borrower);
219     my $accessflagshash;
220
221     $sth = $dbh->prepare("select bit,flag from userflags");
222     $sth->execute;
223     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
224         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
225             $accessflagshash->{$flag} = 1;
226         }
227     }
228     $borrower->{'flags'}     = $flags;
229     $borrower->{'authflags'} = $accessflagshash;
230
231     # Handle setting the true behavior for BlockExpiredPatronOpacActions
232     $borrower->{'BlockExpiredPatronOpacActions'} =
233       C4::Context->preference('BlockExpiredPatronOpacActions')
234       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
235
236     $borrower->{'is_expired'} = 0;
237     $borrower->{'is_expired'} = 1 if
238       defined($borrower->{dateexpiry}) &&
239       $borrower->{'dateexpiry'} ne '0000-00-00' &&
240       Date_to_Days( Today() ) >
241       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
242
243     return ($borrower);    #, $flags, $accessflagshash);
244 }
245
246 =head2 patronflags
247
248  $flags = &patronflags($patron);
249
250 This function is not exported.
251
252 The following will be set where applicable:
253  $flags->{CHARGES}->{amount}        Amount of debt
254  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
255  $flags->{CHARGES}->{message}       Message -- deprecated
256
257  $flags->{CREDITS}->{amount}        Amount of credit
258  $flags->{CREDITS}->{message}       Message -- deprecated
259
260  $flags->{  GNA  }                  Patron has no valid address
261  $flags->{  GNA  }->{noissues}      Set for each GNA
262  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
263
264  $flags->{ LOST  }                  Patron's card reported lost
265  $flags->{ LOST  }->{noissues}      Set for each LOST
266  $flags->{ LOST  }->{message}       Message -- deprecated
267
268  $flags->{DBARRED}                  Set if patron debarred, no access
269  $flags->{DBARRED}->{noissues}      Set for each DBARRED
270  $flags->{DBARRED}->{message}       Message -- deprecated
271
272  $flags->{ NOTES }
273  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
274
275  $flags->{ ODUES }                  Set if patron has overdue books.
276  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
277  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
278  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
279
280  $flags->{WAITING}                  Set if any of patron's reserves are available
281  $flags->{WAITING}->{message}       Message -- deprecated
282  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
283
284 =over 
285
286 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
287 overdue items. Its elements are references-to-hash, each describing an
288 overdue item. The keys are selected fields from the issues, biblio,
289 biblioitems, and items tables of the Koha database.
290
291 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
292 the overdue items, one per line.  Deprecated.
293
294 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
295 available items. Each element is a reference-to-hash whose keys are
296 fields from the reserves table of the Koha database.
297
298 =back
299
300 All the "message" fields that include language generated in this function are deprecated, 
301 because such strings belong properly in the display layer.
302
303 The "message" field that comes from the DB is OK.
304
305 =cut
306
307 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
308 # FIXME rename this function.
309 sub patronflags {
310     my %flags;
311     my ( $patroninformation) = @_;
312     my $dbh=C4::Context->dbh;
313     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
314     if ( $owing > 0 ) {
315         my %flaginfo;
316         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
317         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
318         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
319         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
320             $flaginfo{'noissues'} = 1;
321         }
322         $flags{'CHARGES'} = \%flaginfo;
323     }
324     elsif ( $balance < 0 ) {
325         my %flaginfo;
326         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
327         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
328         $flags{'CREDITS'} = \%flaginfo;
329     }
330
331     # Check the debt of the guarntees of this patron
332     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
333     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
334     if ( defined $no_issues_charge_guarantees ) {
335         my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
336         my @guarantees = $p->guarantees();
337         my $guarantees_non_issues_charges;
338         foreach my $g ( @guarantees ) {
339             my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
340             $guarantees_non_issues_charges += $n;
341         }
342
343         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
344             my %flaginfo;
345             $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
346             $flaginfo{'amount'}  = $guarantees_non_issues_charges;
347             $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
348             $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
349         }
350     }
351
352     if (   $patroninformation->{'gonenoaddress'}
353         && $patroninformation->{'gonenoaddress'} == 1 )
354     {
355         my %flaginfo;
356         $flaginfo{'message'}  = 'Borrower has no valid address.';
357         $flaginfo{'noissues'} = 1;
358         $flags{'GNA'}         = \%flaginfo;
359     }
360     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
361         my %flaginfo;
362         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
363         $flaginfo{'noissues'} = 1;
364         $flags{'LOST'}        = \%flaginfo;
365     }
366     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
367         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
368             my %flaginfo;
369             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
370             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
371             $flaginfo{'noissues'}        = 1;
372             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
373             $flags{'DBARRED'}           = \%flaginfo;
374         }
375     }
376     if (   $patroninformation->{'borrowernotes'}
377         && $patroninformation->{'borrowernotes'} )
378     {
379         my %flaginfo;
380         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
381         $flags{'NOTES'}      = \%flaginfo;
382     }
383     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
384     if ( $odues && $odues > 0 ) {
385         my %flaginfo;
386         $flaginfo{'message'}  = "Yes";
387         $flaginfo{'itemlist'} = $itemsoverdue;
388         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
389             @$itemsoverdue )
390         {
391             $flaginfo{'itemlisttext'} .=
392               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
393         }
394         $flags{'ODUES'} = \%flaginfo;
395     }
396     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
397     my $nowaiting = scalar @itemswaiting;
398     if ( $nowaiting > 0 ) {
399         my %flaginfo;
400         $flaginfo{'message'}  = "Reserved items available";
401         $flaginfo{'itemlist'} = \@itemswaiting;
402         $flags{'WAITING'}     = \%flaginfo;
403     }
404     return ( \%flags );
405 }
406
407
408 =head2 GetMember
409
410   $borrower = &GetMember(%information);
411
412 Retrieve the first patron record meeting on criteria listed in the
413 C<%information> hash, which should contain one or more
414 pairs of borrowers column names and values, e.g.,
415
416    $borrower = GetMember(borrowernumber => id);
417
418 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
419 the C<borrowers> table in the Koha database.
420
421 FIXME: GetMember() is used throughout the code as a lookup
422 on a unique key such as the borrowernumber, but this meaning is not
423 enforced in the routine itself.
424
425 =cut
426
427 #'
428 sub GetMember {
429     my ( %information ) = @_;
430     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
431         #passing mysql's kohaadmin?? Makes no sense as a query
432         return;
433     }
434     my $dbh = C4::Context->dbh;
435     my $select =
436     q{SELECT borrowers.*, categories.category_type, categories.description
437     FROM borrowers 
438     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
439     my $more_p = 0;
440     my @values = ();
441     for (keys %information ) {
442         if ($more_p) {
443             $select .= ' AND ';
444         }
445         else {
446             $more_p++;
447         }
448
449         if (defined $information{$_}) {
450             $select .= "$_ = ?";
451             push @values, $information{$_};
452         }
453         else {
454             $select .= "$_ IS NULL";
455         }
456     }
457     $debug && warn $select, " ",values %information;
458     my $sth = $dbh->prepare("$select");
459     $sth->execute(@values);
460     my $data = $sth->fetchall_arrayref({});
461     #FIXME interface to this routine now allows generation of a result set
462     #so whole array should be returned but bowhere in the current code expects this
463     if (@{$data} ) {
464         return $data->[0];
465     }
466
467     return;
468 }
469
470 =head2 IsMemberBlocked
471
472   my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
473
474 Returns whether a patron is restricted or has overdue items that may result
475 in a block of circulation privileges.
476
477 C<$block_status> can have the following values:
478
479 1 if the patron is currently restricted, in which case
480 C<$count> is the expiration date (9999-12-31 for indefinite)
481
482 -1 if the patron has overdue items, in which case C<$count> is the number of them
483
484 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
485
486 Existing active restrictions are checked before current overdue items.
487
488 =cut
489
490 sub IsMemberBlocked {
491     my $borrowernumber = shift;
492     my $dbh            = C4::Context->dbh;
493
494     my $blockeddate = Koha::Patrons->find( $borrowernumber )->is_debarred;
495
496     return ( 1, $blockeddate ) if $blockeddate;
497
498     # if he have late issues
499     my $sth = $dbh->prepare(
500         "SELECT COUNT(*) as latedocs
501          FROM issues
502          WHERE borrowernumber = ?
503          AND date_due < now()"
504     );
505     $sth->execute($borrowernumber);
506     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
507
508     return ( -1, $latedocs ) if $latedocs > 0;
509
510     return ( 0, 0 );
511 }
512
513 =head2 GetMemberIssuesAndFines
514
515   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
516
517 Returns aggregate data about items borrowed by the patron with the
518 given borrowernumber.
519
520 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
521 number of overdue items the patron currently has borrowed. C<$issue_count> is the
522 number of books the patron currently has borrowed.  C<$total_fines> is
523 the total fine currently due by the borrower.
524
525 =cut
526
527 #'
528 sub GetMemberIssuesAndFines {
529     my ( $borrowernumber ) = @_;
530     my $dbh   = C4::Context->dbh;
531     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
532
533     $debug and warn $query."\n";
534     my $sth = $dbh->prepare($query);
535     $sth->execute($borrowernumber);
536     my $issue_count = $sth->fetchrow_arrayref->[0];
537
538     $sth = $dbh->prepare(
539         "SELECT COUNT(*) FROM issues 
540          WHERE borrowernumber = ? 
541          AND date_due < now()"
542     );
543     $sth->execute($borrowernumber);
544     my $overdue_count = $sth->fetchrow_arrayref->[0];
545
546     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
547     $sth->execute($borrowernumber);
548     my $total_fines = $sth->fetchrow_arrayref->[0];
549
550     return ($overdue_count, $issue_count, $total_fines);
551 }
552
553
554 =head2 ModMember
555
556   my $success = ModMember(borrowernumber => $borrowernumber,
557                                             [ field => value ]... );
558
559 Modify borrower's data.  All date fields should ALREADY be in ISO format.
560
561 return :
562 true on success, or false on failure
563
564 =cut
565
566 sub ModMember {
567     my (%data) = @_;
568     # test to know if you must update or not the borrower password
569     if (exists $data{password}) {
570         if ($data{password} eq '****' or $data{password} eq '') {
571             delete $data{password};
572         } else {
573             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
574                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
575                 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
576             }
577             $data{password} = hash_password($data{password});
578         }
579     }
580
581     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
582
583     # get only the columns of a borrower
584     my $schema = Koha::Database->new()->schema;
585     my @columns = $schema->source('Borrower')->columns;
586     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
587     delete $new_borrower->{flags};
588
589     $new_borrower->{dateofbirth}     ||= undef if exists $new_borrower->{dateofbirth};
590     $new_borrower->{dateenrolled}    ||= undef if exists $new_borrower->{dateenrolled};
591     $new_borrower->{dateexpiry}      ||= undef if exists $new_borrower->{dateexpiry};
592     $new_borrower->{debarred}        ||= undef if exists $new_borrower->{debarred};
593     $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
594
595     my $rs = $schema->resultset('Borrower')->search({
596         borrowernumber => $new_borrower->{borrowernumber},
597      });
598
599     delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
600
601     my $execute_success = $rs->update($new_borrower);
602     if ($execute_success ne '0E0') { # only proceed if the update was a success
603         # If the patron changes to a category with enrollment fee, we add a fee
604         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
605             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
606                 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
607             }
608         }
609
610         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
611         # cronjob will use for syncing with NL
612         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
613             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
614                 'synctype'       => 'norwegianpatrondb',
615                 'borrowernumber' => $data{'borrowernumber'}
616             });
617             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
618             # we can sync as changed. And the "new sync" will pick up all changes since
619             # the patron was created anyway.
620             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
621                 $borrowersync->update( { 'syncstatus' => 'edited' } );
622             }
623             # Set the value of 'sync'
624             $borrowersync->update( { 'sync' => $data{'sync'} } );
625             # Try to do the live sync
626             Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
627         }
628
629         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
630     }
631     return $execute_success;
632 }
633
634 =head2 AddMember
635
636   $borrowernumber = &AddMember(%borrower);
637
638 insert new borrower into table
639
640 (%borrower keys are database columns. Database columns could be
641 different in different versions. Please look into database for correct
642 column names.)
643
644 Returns the borrowernumber upon success
645
646 Returns as undef upon any db error without further processing
647
648 =cut
649
650 #'
651 sub AddMember {
652     my (%data) = @_;
653     my $dbh = C4::Context->dbh;
654     my $schema = Koha::Database->new()->schema;
655
656     # generate a proper login if none provided
657     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
658       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
659
660     # add expiration date if it isn't already there
661     unless ( $data{'dateexpiry'} ) {
662         $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
663     }
664
665     # add enrollment date if it isn't already there
666     unless ( $data{'dateenrolled'} ) {
667         $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
668     }
669
670     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
671     $data{'privacy'} =
672         $patron_category->default_privacy() eq 'default' ? 1
673       : $patron_category->default_privacy() eq 'never'   ? 2
674       : $patron_category->default_privacy() eq 'forever' ? 0
675       :                                                    undef;
676
677     $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
678
679     # Make a copy of the plain text password for later use
680     my $plain_text_password = $data{'password'};
681
682     # create a disabled account if no password provided
683     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
684
685     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
686     $data{'dateofbirth'}     = undef if ( not $data{'dateofbirth'} );
687     $data{'debarred'}        = undef if ( not $data{'debarred'} );
688     $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
689
690     # get only the columns of Borrower
691     my @columns = $schema->source('Borrower')->columns;
692     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
693     $new_member->{checkprevcheckout} ||= 'inherit';
694     delete $new_member->{borrowernumber};
695
696     my $rs = $schema->resultset('Borrower');
697     $data{borrowernumber} = $rs->create($new_member)->id;
698
699     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
700     # cronjob will use for syncing with NL
701     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
702         Koha::Database->new->schema->resultset('BorrowerSync')->create({
703             'borrowernumber' => $data{'borrowernumber'},
704             'synctype'       => 'norwegianpatrondb',
705             'sync'           => 1,
706             'syncstatus'     => 'new',
707             'hashed_pin'     => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
708         });
709     }
710
711     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
712     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
713
714     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
715
716     return $data{borrowernumber};
717 }
718
719 =head2 Check_Userid
720
721     my $uniqueness = Check_Userid($userid,$borrowernumber);
722
723     $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 != '').
724
725     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.
726
727     return :
728         0 for not unique (i.e. this $userid already exists)
729         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
730
731 =cut
732
733 sub Check_Userid {
734     my ( $uid, $borrowernumber ) = @_;
735
736     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
737
738     return 0 if ( $uid eq C4::Context->config('user') );
739
740     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
741
742     my $params;
743     $params->{userid} = $uid;
744     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
745
746     my $count = $rs->count( $params );
747
748     return $count ? 0 : 1;
749 }
750
751 =head2 Generate_Userid
752
753     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
754
755     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
756
757     $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.
758
759     return :
760         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).
761
762 =cut
763
764 sub Generate_Userid {
765   my ($borrowernumber, $firstname, $surname) = @_;
766   my $newuid;
767   my $offset = 0;
768   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
769   do {
770     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
771     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
772     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
773     $newuid = unac_string('utf-8',$newuid);
774     $newuid .= $offset unless $offset == 0;
775     $offset++;
776
777    } while (!Check_Userid($newuid,$borrowernumber));
778
779    return $newuid;
780 }
781
782 =head2 fixup_cardnumber
783
784 Warning: The caller is responsible for locking the members table in write
785 mode, to avoid database corruption.
786
787 =cut
788
789 use vars qw( @weightings );
790 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
791
792 sub fixup_cardnumber {
793     my ($cardnumber) = @_;
794     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
795
796     # Find out whether member numbers should be generated
797     # automatically. Should be either "1" or something else.
798     # Defaults to "0", which is interpreted as "no".
799
800     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
801     ($autonumber_members) or return $cardnumber;
802     my $checkdigit = C4::Context->preference('checkdigit');
803     my $dbh = C4::Context->dbh;
804     if ( $checkdigit and $checkdigit eq 'katipo' ) {
805
806         # if checkdigit is selected, calculate katipo-style cardnumber.
807         # otherwise, just use the max()
808         # purpose: generate checksum'd member numbers.
809         # We'll assume we just got the max value of digits 2-8 of member #'s
810         # from the database and our job is to increment that by one,
811         # determine the 1st and 9th digits and return the full string.
812         my $sth = $dbh->prepare(
813             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
814         );
815         $sth->execute;
816         my $data = $sth->fetchrow_hashref;
817         $cardnumber = $data->{new_num};
818         if ( !$cardnumber ) {    # If DB has no values,
819             $cardnumber = 1000000;    # start at 1000000
820         } else {
821             $cardnumber += 1;
822         }
823
824         my $sum = 0;
825         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
826             # read weightings, left to right, 1 char at a time
827             my $temp1 = $weightings[$i];
828
829             # sequence left to right, 1 char at a time
830             my $temp2 = substr( $cardnumber, $i, 1 );
831
832             # mult each char 1-7 by its corresponding weighting
833             $sum += $temp1 * $temp2;
834         }
835
836         my $rem = ( $sum % 11 );
837         $rem = 'X' if $rem == 10;
838
839         return "V$cardnumber$rem";
840      } else {
841
842         my $sth = $dbh->prepare(
843             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
844         );
845         $sth->execute;
846         my ($result) = $sth->fetchrow;
847         return $result + 1;
848     }
849     return $cardnumber;     # just here as a fallback/reminder 
850 }
851
852 =head2 GetPendingIssues
853
854   my $issues = &GetPendingIssues(@borrowernumber);
855
856 Looks up what the patron with the given borrowernumber has borrowed.
857
858 C<&GetPendingIssues> returns a
859 reference-to-array where each element is a reference-to-hash; the
860 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
861 The keys include C<biblioitems> fields except marc and marcxml.
862
863 =cut
864
865 sub GetPendingIssues {
866     my @borrowernumbers = @_;
867
868     unless (@borrowernumbers ) { # return a ref_to_array
869         return \@borrowernumbers; # to not cause surprise to caller
870     }
871
872     # Borrowers part of the query
873     my $bquery = '';
874     for (my $i = 0; $i < @borrowernumbers; $i++) {
875         $bquery .= ' issues.borrowernumber = ?';
876         if ($i < $#borrowernumbers ) {
877             $bquery .= ' OR';
878         }
879     }
880
881     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
882     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
883     # FIXME: circ/ciculation.pl tries to sort by timestamp!
884     # FIXME: namespace collision: other collisions possible.
885     # FIXME: most of this data isn't really being used by callers.
886     my $query =
887    "SELECT issues.*,
888             items.*,
889            biblio.*,
890            biblioitems.volume,
891            biblioitems.number,
892            biblioitems.itemtype,
893            biblioitems.isbn,
894            biblioitems.issn,
895            biblioitems.publicationyear,
896            biblioitems.publishercode,
897            biblioitems.volumedate,
898            biblioitems.volumedesc,
899            biblioitems.lccn,
900            biblioitems.url,
901            borrowers.firstname,
902            borrowers.surname,
903            borrowers.cardnumber,
904            issues.timestamp AS timestamp,
905            issues.renewals  AS renewals,
906            issues.borrowernumber AS borrowernumber,
907             items.renewals  AS totalrenewals
908     FROM   issues
909     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
910     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
911     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
912     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
913     WHERE
914       $bquery
915     ORDER BY issues.issuedate"
916     ;
917
918     my $sth = C4::Context->dbh->prepare($query);
919     $sth->execute(@borrowernumbers);
920     my $data = $sth->fetchall_arrayref({});
921     my $today = dt_from_string;
922     foreach (@{$data}) {
923         if ($_->{issuedate}) {
924             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
925         }
926         $_->{date_due_sql} = $_->{date_due};
927         # FIXME no need to have this value
928         $_->{date_due} or next;
929         $_->{date_due_sql} = $_->{date_due};
930         # FIXME no need to have this value
931         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
932         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
933             $_->{overdue} = 1;
934         }
935     }
936     return $data;
937 }
938
939 =head2 GetAllIssues
940
941   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
942
943 Looks up what the patron with the given borrowernumber has borrowed,
944 and sorts the results.
945
946 C<$sortkey> is the name of a field on which to sort the results. This
947 should be the name of a field in the C<issues>, C<biblio>,
948 C<biblioitems>, or C<items> table in the Koha database.
949
950 C<$limit> is the maximum number of results to return.
951
952 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
953 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
954 C<items> tables of the Koha database.
955
956 =cut
957
958 #'
959 sub GetAllIssues {
960     my ( $borrowernumber, $order, $limit ) = @_;
961
962     return unless $borrowernumber;
963     $order = 'date_due desc' unless $order;
964
965     my $dbh = C4::Context->dbh;
966     my $query =
967 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
968   FROM issues 
969   LEFT JOIN items on items.itemnumber=issues.itemnumber
970   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
971   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
972   WHERE borrowernumber=? 
973   UNION ALL
974   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
975   FROM old_issues 
976   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
977   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
978   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
979   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
980   order by ' . $order;
981     if ($limit) {
982         $query .= " limit $limit";
983     }
984
985     my $sth = $dbh->prepare($query);
986     $sth->execute( $borrowernumber, $borrowernumber );
987     return $sth->fetchall_arrayref( {} );
988 }
989
990
991 =head2 GetMemberAccountRecords
992
993   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
994
995 Looks up accounting data for the patron with the given borrowernumber.
996
997 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
998 reference-to-array, where each element is a reference-to-hash; the
999 keys are the fields of the C<accountlines> table in the Koha database.
1000 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1001 total amount outstanding for all of the account lines.
1002
1003 =cut
1004
1005 sub GetMemberAccountRecords {
1006     my ($borrowernumber) = @_;
1007     my $dbh = C4::Context->dbh;
1008     my @acctlines;
1009     my $numlines = 0;
1010     my $strsth      = qq(
1011                         SELECT * 
1012                         FROM accountlines 
1013                         WHERE borrowernumber=?);
1014     $strsth.=" ORDER BY accountlines_id desc";
1015     my $sth= $dbh->prepare( $strsth );
1016     $sth->execute( $borrowernumber );
1017
1018     my $total = 0;
1019     while ( my $data = $sth->fetchrow_hashref ) {
1020         if ( $data->{itemnumber} ) {
1021             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1022             $data->{biblionumber} = $biblio->{biblionumber};
1023             $data->{title}        = $biblio->{title};
1024         }
1025         $acctlines[$numlines] = $data;
1026         $numlines++;
1027         $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1028     }
1029     $total /= 1000;
1030     return ( $total, \@acctlines,$numlines);
1031 }
1032
1033 =head2 GetMemberAccountBalance
1034
1035   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1036
1037 Calculates amount immediately owing by the patron - non-issue charges.
1038 Based on GetMemberAccountRecords.
1039 Charges exempt from non-issue are:
1040 * Res (reserves)
1041 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1042 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1043
1044 =cut
1045
1046 sub GetMemberAccountBalance {
1047     my ($borrowernumber) = @_;
1048
1049     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1050
1051     my @not_fines;
1052     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1053     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1054     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1055         my $dbh = C4::Context->dbh;
1056         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1057         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1058     }
1059     my %not_fine = map {$_ => 1} @not_fines;
1060
1061     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1062     my $other_charges = 0;
1063     foreach (@$acctlines) {
1064         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1065     }
1066
1067     return ( $total, $total - $other_charges, $other_charges);
1068 }
1069
1070 =head2 GetBorNotifyAcctRecord
1071
1072   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1073
1074 Looks up accounting data for the patron with the given borrowernumber per file number.
1075
1076 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1077 reference-to-array, where each element is a reference-to-hash; the
1078 keys are the fields of the C<accountlines> table in the Koha database.
1079 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1080 total amount outstanding for all of the account lines.
1081
1082 =cut
1083
1084 sub GetBorNotifyAcctRecord {
1085     my ( $borrowernumber, $notifyid ) = @_;
1086     my $dbh = C4::Context->dbh;
1087     my @acctlines;
1088     my $numlines = 0;
1089     my $sth = $dbh->prepare(
1090             "SELECT * 
1091                 FROM accountlines 
1092                 WHERE borrowernumber=? 
1093                     AND notify_id=? 
1094                     AND amountoutstanding != '0' 
1095                 ORDER BY notify_id,accounttype
1096                 ");
1097
1098     $sth->execute( $borrowernumber, $notifyid );
1099     my $total = 0;
1100     while ( my $data = $sth->fetchrow_hashref ) {
1101         if ( $data->{itemnumber} ) {
1102             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1103             $data->{biblionumber} = $biblio->{biblionumber};
1104             $data->{title}        = $biblio->{title};
1105         }
1106         $acctlines[$numlines] = $data;
1107         $numlines++;
1108         $total += int(100 * $data->{'amountoutstanding'});
1109     }
1110     $total /= 100;
1111     return ( $total, \@acctlines, $numlines );
1112 }
1113
1114 sub checkcardnumber {
1115     my ( $cardnumber, $borrowernumber ) = @_;
1116
1117     # If cardnumber is null, we assume they're allowed.
1118     return 0 unless defined $cardnumber;
1119
1120     my $dbh = C4::Context->dbh;
1121     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1122     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1123     my $sth = $dbh->prepare($query);
1124     $sth->execute(
1125         $cardnumber,
1126         ( $borrowernumber ? $borrowernumber : () )
1127     );
1128
1129     return 1 if $sth->fetchrow_hashref;
1130
1131     my ( $min_length, $max_length ) = get_cardnumber_length();
1132     return 2
1133         if length $cardnumber > $max_length
1134         or length $cardnumber < $min_length;
1135
1136     return 0;
1137 }
1138
1139 =head2 get_cardnumber_length
1140
1141     my ($min, $max) = C4::Members::get_cardnumber_length()
1142
1143 Returns the minimum and maximum length for patron cardnumbers as
1144 determined by the CardnumberLength system preference, the
1145 BorrowerMandatoryField system preference, and the width of the
1146 database column.
1147
1148 =cut
1149
1150 sub get_cardnumber_length {
1151     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1152     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1153     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1154         # Is integer and length match
1155         if ( $cardnumber_length =~ m|^\d+$| ) {
1156             $min = $max = $cardnumber_length
1157                 if $cardnumber_length >= $min
1158                     and $cardnumber_length <= $max;
1159         }
1160         # Else assuming it is a range
1161         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1162             $min = $1 if $1 and $min < $1;
1163             $max = $2 if $2 and $max > $2;
1164         }
1165
1166     }
1167     return ( $min, $max );
1168 }
1169
1170 =head2 GetFirstValidEmailAddress
1171
1172   $email = GetFirstValidEmailAddress($borrowernumber);
1173
1174 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1175 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1176 addresses.
1177
1178 =cut
1179
1180 sub GetFirstValidEmailAddress {
1181     my $borrowernumber = shift;
1182     my $dbh = C4::Context->dbh;
1183     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1184     $sth->execute( $borrowernumber );
1185     my $data = $sth->fetchrow_hashref;
1186
1187     if ($data->{'email'}) {
1188        return $data->{'email'};
1189     } elsif ($data->{'emailpro'}) {
1190        return $data->{'emailpro'};
1191     } elsif ($data->{'B_email'}) {
1192        return $data->{'B_email'};
1193     } else {
1194        return '';
1195     }
1196 }
1197
1198 =head2 GetNoticeEmailAddress
1199
1200   $email = GetNoticeEmailAddress($borrowernumber);
1201
1202 Return the email address of borrower used for notices, given the borrowernumber.
1203 Returns the empty string if no email address.
1204
1205 =cut
1206
1207 sub GetNoticeEmailAddress {
1208     my $borrowernumber = shift;
1209
1210     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1211     # if syspref is set to 'first valid' (value == OFF), look up email address
1212     if ( $which_address eq 'OFF' ) {
1213         return GetFirstValidEmailAddress($borrowernumber);
1214     }
1215     # specified email address field
1216     my $dbh = C4::Context->dbh;
1217     my $sth = $dbh->prepare( qq{
1218         SELECT $which_address AS primaryemail
1219         FROM borrowers
1220         WHERE borrowernumber=?
1221     } );
1222     $sth->execute($borrowernumber);
1223     my $data = $sth->fetchrow_hashref;
1224     return $data->{'primaryemail'} || '';
1225 }
1226
1227 =head2 GetExpiryDate 
1228
1229   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1230
1231 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1232 Return date is also in ISO format.
1233
1234 =cut
1235
1236 sub GetExpiryDate {
1237     my ( $categorycode, $dateenrolled ) = @_;
1238     my $enrolments;
1239     if ($categorycode) {
1240         my $dbh = C4::Context->dbh;
1241         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1242         $sth->execute($categorycode);
1243         $enrolments = $sth->fetchrow_hashref;
1244     }
1245     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1246     my @date = split (/-/,$dateenrolled);
1247     if($enrolments->{enrolmentperiod}){
1248         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1249     }else{
1250         return $enrolments->{enrolmentperioddate};
1251     }
1252 }
1253
1254 =head2 GetUpcomingMembershipExpires
1255
1256     my $expires = GetUpcomingMembershipExpires({
1257         branch => $branch, before => $before, after => $after,
1258     });
1259
1260     $branch is an optional branch code.
1261     $before/$after is an optional number of days before/after the date that
1262     is set by the preference MembershipExpiryDaysNotice.
1263     If the pref would be 14, before 2 and after 3, you will get all expires
1264     from 12 to 17 days.
1265
1266 =cut
1267
1268 sub GetUpcomingMembershipExpires {
1269     my ( $params ) = @_;
1270     my $before = $params->{before} || 0;
1271     my $after  = $params->{after} || 0;
1272     my $branch = $params->{branch};
1273
1274     my $dbh = C4::Context->dbh;
1275     my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1276     my $date1 = dt_from_string->add( days => $days - $before );
1277     my $date2 = dt_from_string->add( days => $days + $after );
1278     $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1279     $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1280
1281     my $query = q|
1282         SELECT borrowers.*, categories.description,
1283         branches.branchname, branches.branchemail FROM borrowers
1284         LEFT JOIN branches USING (branchcode)
1285         LEFT JOIN categories USING (categorycode)
1286     |;
1287     if( $branch ) {
1288         $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1289     } else {
1290         $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1291     }
1292
1293     my $sth = $dbh->prepare( $query );
1294     my @pars = $branch? ( $branch ): ();
1295     push @pars, $date1, $date2;
1296     $sth->execute( @pars );
1297     my $results = $sth->fetchall_arrayref( {} );
1298     return $results;
1299 }
1300
1301 =head2 GetborCatFromCatType
1302
1303   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1304
1305 Looks up the different types of borrowers in the database. Returns two
1306 elements: a reference-to-array, which lists the borrower category
1307 codes, and a reference-to-hash, which maps the borrower category codes
1308 to category descriptions.
1309
1310 =cut
1311
1312 #'
1313 sub GetborCatFromCatType {
1314     my ( $category_type, $action, $no_branch_limit ) = @_;
1315
1316     my $branch_limit = $no_branch_limit
1317         ? 0
1318         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1319
1320     # FIXME - This API  seems both limited and dangerous.
1321     my $dbh     = C4::Context->dbh;
1322
1323     my $request = qq{
1324         SELECT categories.categorycode, categories.description
1325         FROM categories
1326     };
1327     $request .= qq{
1328         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1329     } if $branch_limit;
1330     if($action) {
1331         $request .= " $action ";
1332         $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1333     } else {
1334         $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1335     }
1336     $request .= " ORDER BY categorycode";
1337
1338     my $sth = $dbh->prepare($request);
1339     $sth->execute(
1340         $action ? $category_type : (),
1341         $branch_limit ? $branch_limit : ()
1342     );
1343
1344     my %labels;
1345     my @codes;
1346
1347     while ( my $data = $sth->fetchrow_hashref ) {
1348         push @codes, $data->{'categorycode'};
1349         $labels{ $data->{'categorycode'} } = $data->{'description'};
1350     }
1351     $sth->finish;
1352     return ( \@codes, \%labels );
1353 }
1354
1355 =head2 GetBorrowercategory
1356
1357   $hashref = &GetBorrowercategory($categorycode);
1358
1359 Given the borrower's category code, the function returns the corresponding
1360 data hashref for a comprehensive information display.
1361
1362 =cut
1363
1364 sub GetBorrowercategory {
1365     my ($catcode) = @_;
1366     my $dbh       = C4::Context->dbh;
1367     if ($catcode){
1368         my $sth       =
1369         $dbh->prepare(
1370     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1371     FROM categories 
1372     WHERE categorycode = ?"
1373         );
1374         $sth->execute($catcode);
1375         my $data =
1376         $sth->fetchrow_hashref;
1377         return $data;
1378     } 
1379     return;  
1380 }    # sub getborrowercategory
1381
1382
1383 =head2 GetBorrowerCategorycode
1384
1385     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1386
1387 Given the borrowernumber, the function returns the corresponding categorycode
1388
1389 =cut
1390
1391 sub GetBorrowerCategorycode {
1392     my ( $borrowernumber ) = @_;
1393     my $dbh = C4::Context->dbh;
1394     my $sth = $dbh->prepare( qq{
1395         SELECT categorycode
1396         FROM borrowers
1397         WHERE borrowernumber = ?
1398     } );
1399     $sth->execute( $borrowernumber );
1400     return $sth->fetchrow;
1401 }
1402
1403 =head2 GetBorrowercategoryList
1404
1405   $arrayref_hashref = &GetBorrowercategoryList;
1406 If no category code provided, the function returns all the categories.
1407
1408 =cut
1409
1410 sub GetBorrowercategoryList {
1411     my $no_branch_limit = @_ ? shift : 0;
1412     my $branch_limit = $no_branch_limit
1413         ? 0
1414         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1415     my $dbh       = C4::Context->dbh;
1416     my $query = "SELECT categories.* FROM categories";
1417     $query .= qq{
1418         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1419         WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1420     } if $branch_limit;
1421     $query .= " ORDER BY description";
1422     my $sth = $dbh->prepare( $query );
1423     $sth->execute( $branch_limit ? $branch_limit : () );
1424     my $data = $sth->fetchall_arrayref( {} );
1425     $sth->finish;
1426     return $data;
1427 }    # sub getborrowercategory
1428
1429 =head2 GetAge
1430
1431   $dateofbirth,$date = &GetAge($date);
1432
1433 this function return the borrowers age with the value of dateofbirth
1434
1435 =cut
1436
1437 #'
1438 sub GetAge{
1439     my ( $date, $date_ref ) = @_;
1440
1441     if ( not defined $date_ref ) {
1442         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1443     }
1444
1445     my ( $year1, $month1, $day1 ) = split /-/, $date;
1446     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1447
1448     my $age = $year2 - $year1;
1449     if ( $month1 . $day1 > $month2 . $day2 ) {
1450         $age--;
1451     }
1452
1453     return $age;
1454 }    # sub get_age
1455
1456 =head2 SetAge
1457
1458   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1459   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1460   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1461
1462   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1463   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1464
1465 This function sets the borrower's dateofbirth to match the given age.
1466 Optionally relative to the given $datetime_reference.
1467
1468 @PARAM1 koha.borrowers-object
1469 @PARAM2 DateTime::Duration-object as the desired age
1470         OR a ISO 8601 Date. (To make the API more pleasant)
1471 @PARAM3 DateTime-object as the relative date, defaults to now().
1472 RETURNS The given borrower reference @PARAM1.
1473 DIES    If there was an error with the ISO Date handling.
1474
1475 =cut
1476
1477 #'
1478 sub SetAge{
1479     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1480     $datetime_ref = DateTime->now() unless $datetime_ref;
1481
1482     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1483         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1484             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1485         }
1486         else {
1487             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1488         }
1489     }
1490
1491     my $new_datetime_ref = $datetime_ref->clone();
1492     $new_datetime_ref->subtract_duration( $datetimeduration );
1493
1494     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1495
1496     return $borrower;
1497 }    # sub SetAge
1498
1499 =head2 GetSortDetails (OUEST-PROVENCE)
1500
1501   ($lib) = &GetSortDetails($category,$sortvalue);
1502
1503 Returns the authorized value  details
1504 C<&$lib>return value of authorized value details
1505 C<&$sortvalue>this is the value of authorized value 
1506 C<&$category>this is the value of authorized value category
1507
1508 =cut
1509
1510 sub GetSortDetails {
1511     my ( $category, $sortvalue ) = @_;
1512     my $dbh   = C4::Context->dbh;
1513     my $query = qq|SELECT lib 
1514         FROM authorised_values 
1515         WHERE category=?
1516         AND authorised_value=? |;
1517     my $sth = $dbh->prepare($query);
1518     $sth->execute( $category, $sortvalue );
1519     my $lib = $sth->fetchrow;
1520     return ($lib) if ($lib);
1521     return ($sortvalue) unless ($lib);
1522 }
1523
1524 =head2 MoveMemberToDeleted
1525
1526   $result = &MoveMemberToDeleted($borrowernumber);
1527
1528 Copy the record from borrowers to deletedborrowers table.
1529 The routine returns 1 for success, undef for failure.
1530
1531 =cut
1532
1533 sub MoveMemberToDeleted {
1534     my ($member) = shift or return;
1535
1536     my $schema       = Koha::Database->new()->schema();
1537     my $borrowers_rs = $schema->resultset('Borrower');
1538     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1539     my $borrower = $borrowers_rs->find($member);
1540     return unless $borrower;
1541
1542     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1543
1544     return $deleted ? 1 : undef;
1545 }
1546
1547 =head2 DelMember
1548
1549     DelMember($borrowernumber);
1550
1551 This function remove directly a borrower whitout writing it on deleteborrower.
1552 + Deletes reserves for the borrower
1553
1554 =cut
1555
1556 sub DelMember {
1557     my $dbh            = C4::Context->dbh;
1558     my $borrowernumber = shift;
1559     #warn "in delmember with $borrowernumber";
1560     return unless $borrowernumber;    # borrowernumber is mandatory.
1561     # Delete Patron's holds
1562     my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1563     $_->delete for @holds;
1564
1565     my $query = "
1566        DELETE
1567        FROM borrowers
1568        WHERE borrowernumber = ?
1569    ";
1570     my $sth = $dbh->prepare($query);
1571     $sth->execute($borrowernumber);
1572     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1573     return $sth->rows;
1574 }
1575
1576 =head2 HandleDelBorrower
1577
1578      HandleDelBorrower($borrower);
1579
1580 When a member is deleted (DelMember in Members.pm), you should call me first.
1581 This routine deletes/moves lists and entries for the deleted member/borrower.
1582 Lists owned by the borrower are deleted, but entries from the borrower to
1583 other lists are kept.
1584
1585 =cut
1586
1587 sub HandleDelBorrower {
1588     my ($borrower)= @_;
1589     my $query;
1590     my $dbh = C4::Context->dbh;
1591
1592     #Delete all lists and all shares of this borrower
1593     #Consistent with the approach Koha uses on deleting individual lists
1594     #Note that entries in virtualshelfcontents added by this borrower to
1595     #lists of others will be handled by a table constraint: the borrower
1596     #is set to NULL in those entries.
1597     $query="DELETE FROM virtualshelves WHERE owner=?";
1598     $dbh->do($query,undef,($borrower));
1599
1600     #NOTE:
1601     #We could handle the above deletes via a constraint too.
1602     #But a new BZ report 11889 has been opened to discuss another approach.
1603     #Instead of deleting we could also disown lists (based on a pref).
1604     #In that way we could save shared and public lists.
1605     #The current table constraints support that idea now.
1606     #This pref should then govern the results of other routines/methods such as
1607     #Koha::Virtualshelf->new->delete too.
1608 }
1609
1610 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1611
1612     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1613
1614 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1615 Returns ISO date.
1616
1617 =cut
1618
1619 sub ExtendMemberSubscriptionTo {
1620     my ( $borrowerid,$date) = @_;
1621     my $dbh = C4::Context->dbh;
1622     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1623     unless ($date){
1624       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1625                                         eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'}  ), dateonly => 1, dateformat => 'iso' } ); }
1626                                         :
1627                                         output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1628       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1629     }
1630     my $sth = $dbh->do(<<EOF);
1631 UPDATE borrowers 
1632 SET  dateexpiry='$date' 
1633 WHERE borrowernumber='$borrowerid'
1634 EOF
1635
1636     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1637
1638     logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1639     return $date if ($sth);
1640     return 0;
1641 }
1642
1643 =head2 GetTitles (OUEST-PROVENCE)
1644
1645   ($borrowertitle)= &GetTitles();
1646
1647 Looks up the different title . Returns array  with all borrowers title
1648
1649 =cut
1650
1651 sub GetTitles {
1652     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1653     unshift( @borrowerTitle, "" );
1654     my $count=@borrowerTitle;
1655     if ($count == 1){
1656         return ();
1657     }
1658     else {
1659         return ( \@borrowerTitle);
1660     }
1661 }
1662
1663 =head2 GetHideLostItemsPreference
1664
1665   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1666
1667 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1668 C<&$hidelostitemspref>return value of function, 0 or 1
1669
1670 =cut
1671
1672 sub GetHideLostItemsPreference {
1673     my ($borrowernumber) = @_;
1674     my $dbh = C4::Context->dbh;
1675     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1676     my $sth = $dbh->prepare($query);
1677     $sth->execute($borrowernumber);
1678     my $hidelostitems = $sth->fetchrow;    
1679     return $hidelostitems;    
1680 }
1681
1682 =head2 GetBorrowersToExpunge
1683
1684   $borrowers = &GetBorrowersToExpunge(
1685       not_borrowed_since => $not_borrowed_since,
1686       expired_before       => $expired_before,
1687       category_code        => $category_code,
1688       patron_list_id       => $patron_list_id,
1689       branchcode           => $branchcode
1690   );
1691
1692   This function get all borrowers based on the given criteria.
1693
1694 =cut
1695
1696 sub GetBorrowersToExpunge {
1697
1698     my $params = shift;
1699     my $filterdate       = $params->{'not_borrowed_since'};
1700     my $filterexpiry     = $params->{'expired_before'};
1701     my $filtercategory   = $params->{'category_code'};
1702     my $filterbranch     = $params->{'branchcode'} ||
1703                         ((C4::Context->preference('IndependentBranches')
1704                              && C4::Context->userenv 
1705                              && !C4::Context->IsSuperLibrarian()
1706                              && C4::Context->userenv->{branch})
1707                          ? C4::Context->userenv->{branch}
1708                          : "");  
1709     my $filterpatronlist = $params->{'patron_list_id'};
1710
1711     my $dbh   = C4::Context->dbh;
1712     my $query = q|
1713         SELECT borrowers.borrowernumber,
1714                MAX(old_issues.timestamp) AS latestissue,
1715                MAX(issues.timestamp) AS currentissue
1716         FROM   borrowers
1717         JOIN   categories USING (categorycode)
1718         LEFT JOIN (
1719             SELECT guarantorid
1720             FROM borrowers
1721             WHERE guarantorid IS NOT NULL
1722                 AND guarantorid <> 0
1723         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1724         LEFT JOIN old_issues USING (borrowernumber)
1725         LEFT JOIN issues USING (borrowernumber)|;
1726     if ( $filterpatronlist  ){
1727         $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1728     }
1729     $query .= q| WHERE  category_type <> 'S'
1730         AND tmp.guarantorid IS NULL
1731    |;
1732     my @query_params;
1733     if ( $filterbranch && $filterbranch ne "" ) {
1734         $query.= " AND borrowers.branchcode = ? ";
1735         push( @query_params, $filterbranch );
1736     }
1737     if ( $filterexpiry ) {
1738         $query .= " AND dateexpiry < ? ";
1739         push( @query_params, $filterexpiry );
1740     }
1741     if ( $filtercategory ) {
1742         $query .= " AND categorycode = ? ";
1743         push( @query_params, $filtercategory );
1744     }
1745     if ( $filterpatronlist ){
1746         $query.=" AND patron_list_id = ? ";
1747         push( @query_params, $filterpatronlist );
1748     }
1749     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1750     if ( $filterdate ) {
1751         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1752         push @query_params,$filterdate;
1753     }
1754     warn $query if $debug;
1755
1756     my $sth = $dbh->prepare($query);
1757     if (scalar(@query_params)>0){  
1758         $sth->execute(@query_params);
1759     }
1760     else {
1761         $sth->execute;
1762     }
1763     
1764     my @results;
1765     while ( my $data = $sth->fetchrow_hashref ) {
1766         push @results, $data;
1767     }
1768     return \@results;
1769 }
1770
1771 =head2 GetBorrowersWhoHaveNeverBorrowed
1772
1773   $results = &GetBorrowersWhoHaveNeverBorrowed
1774
1775 This function get all borrowers who have never borrowed.
1776
1777 I<$result> is a ref to an array which all elements are a hasref.
1778
1779 =cut
1780
1781 sub GetBorrowersWhoHaveNeverBorrowed {
1782     my $filterbranch = shift || 
1783                         ((C4::Context->preference('IndependentBranches')
1784                              && C4::Context->userenv 
1785                              && !C4::Context->IsSuperLibrarian()
1786                              && C4::Context->userenv->{branch})
1787                          ? C4::Context->userenv->{branch}
1788                          : "");  
1789     my $dbh   = C4::Context->dbh;
1790     my $query = "
1791         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1792         FROM   borrowers
1793           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1794         WHERE issues.borrowernumber IS NULL
1795    ";
1796     my @query_params;
1797     if ($filterbranch && $filterbranch ne ""){ 
1798         $query.=" AND borrowers.branchcode= ?";
1799         push @query_params,$filterbranch;
1800     }
1801     warn $query if $debug;
1802   
1803     my $sth = $dbh->prepare($query);
1804     if (scalar(@query_params)>0){  
1805         $sth->execute(@query_params);
1806     } 
1807     else {
1808         $sth->execute;
1809     }      
1810     
1811     my @results;
1812     while ( my $data = $sth->fetchrow_hashref ) {
1813         push @results, $data;
1814     }
1815     return \@results;
1816 }
1817
1818 =head2 GetBorrowersWithIssuesHistoryOlderThan
1819
1820   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1821
1822 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1823
1824 I<$result> is a ref to an array which all elements are a hashref.
1825 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1826
1827 =cut
1828
1829 sub GetBorrowersWithIssuesHistoryOlderThan {
1830     my $dbh  = C4::Context->dbh;
1831     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1832     my $filterbranch = shift || 
1833                         ((C4::Context->preference('IndependentBranches')
1834                              && C4::Context->userenv 
1835                              && !C4::Context->IsSuperLibrarian()
1836                              && C4::Context->userenv->{branch})
1837                          ? C4::Context->userenv->{branch}
1838                          : "");  
1839     my $query = "
1840        SELECT count(borrowernumber) as n,borrowernumber
1841        FROM old_issues
1842        WHERE returndate < ?
1843          AND borrowernumber IS NOT NULL 
1844     "; 
1845     my @query_params;
1846     push @query_params, $date;
1847     if ($filterbranch){
1848         $query.="   AND branchcode = ?";
1849         push @query_params, $filterbranch;
1850     }    
1851     $query.=" GROUP BY borrowernumber ";
1852     warn $query if $debug;
1853     my $sth = $dbh->prepare($query);
1854     $sth->execute(@query_params);
1855     my @results;
1856
1857     while ( my $data = $sth->fetchrow_hashref ) {
1858         push @results, $data;
1859     }
1860     return \@results;
1861 }
1862
1863 =head2 GetBorrowersNamesAndLatestIssue
1864
1865   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1866
1867 this function get borrowers Names and surnames and Issue information.
1868
1869 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1870 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1871
1872 =cut
1873
1874 sub GetBorrowersNamesAndLatestIssue {
1875     my $dbh  = C4::Context->dbh;
1876     my @borrowernumbers=@_;  
1877     my $query = "
1878        SELECT surname,lastname, phone, email,max(timestamp)
1879        FROM borrowers 
1880          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1881        GROUP BY borrowernumber
1882    ";
1883     my $sth = $dbh->prepare($query);
1884     $sth->execute;
1885     my $results = $sth->fetchall_arrayref({});
1886     return $results;
1887 }
1888
1889 =head2 IssueSlip
1890
1891   IssueSlip($branchcode, $borrowernumber, $quickslip)
1892
1893   Returns letter hash ( see C4::Letters::GetPreparedLetter )
1894
1895   $quickslip is boolean, to indicate whether we want a quick slip
1896
1897   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1898
1899   Both slips:
1900
1901       <<branches.*>>
1902       <<borrowers.*>>
1903
1904   ISSUESLIP:
1905
1906       <checkedout>
1907          <<biblio.*>>
1908          <<items.*>>
1909          <<biblioitems.*>>
1910          <<issues.*>>
1911       </checkedout>
1912
1913       <overdue>
1914          <<biblio.*>>
1915          <<items.*>>
1916          <<biblioitems.*>>
1917          <<issues.*>>
1918       </overdue>
1919
1920       <news>
1921          <<opac_news.*>>
1922       </news>
1923
1924   ISSUEQSLIP:
1925
1926       <checkedout>
1927          <<biblio.*>>
1928          <<items.*>>
1929          <<biblioitems.*>>
1930          <<issues.*>>
1931       </checkedout>
1932
1933   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1934
1935 =cut
1936
1937 sub IssueSlip {
1938     my ($branch, $borrowernumber, $quickslip) = @_;
1939
1940     # FIXME Check callers before removing this statement
1941     #return unless $borrowernumber;
1942
1943     my @issues = @{ GetPendingIssues($borrowernumber) };
1944
1945     for my $issue (@issues) {
1946         $issue->{date_due} = $issue->{date_due_sql};
1947         if ($quickslip) {
1948             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1949             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1950                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1951                   $issue->{now} = 1;
1952             };
1953         }
1954     }
1955
1956     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1957     @issues = sort {
1958         my $s = $b->{timestamp} <=> $a->{timestamp};
1959         $s == 0 ?
1960              $b->{issuedate} <=> $a->{issuedate} : $s;
1961     } @issues;
1962
1963     my ($letter_code, %repeat);
1964     if ( $quickslip ) {
1965         $letter_code = 'ISSUEQSLIP';
1966         %repeat =  (
1967             'checkedout' => [ map {
1968                 'biblio'       => $_,
1969                 'items'        => $_,
1970                 'biblioitems'  => $_,
1971                 'issues'       => $_,
1972             }, grep { $_->{'now'} } @issues ],
1973         );
1974     }
1975     else {
1976         $letter_code = 'ISSUESLIP';
1977         %repeat =  (
1978             'checkedout' => [ map {
1979                 'biblio'       => $_,
1980                 'items'        => $_,
1981                 'biblioitems'  => $_,
1982                 'issues'       => $_,
1983             }, grep { !$_->{'overdue'} } @issues ],
1984
1985             'overdue' => [ map {
1986                 'biblio'       => $_,
1987                 'items'        => $_,
1988                 'biblioitems'  => $_,
1989                 'issues'       => $_,
1990             }, grep { $_->{'overdue'} } @issues ],
1991
1992             'news' => [ map {
1993                 $_->{'timestamp'} = $_->{'newdate'};
1994                 { opac_news => $_ }
1995             } @{ GetNewsToDisplay("slip",$branch) } ],
1996         );
1997     }
1998
1999     return  C4::Letters::GetPreparedLetter (
2000         module => 'circulation',
2001         letter_code => $letter_code,
2002         branchcode => $branch,
2003         tables => {
2004             'branches'    => $branch,
2005             'borrowers'   => $borrowernumber,
2006         },
2007         repeat => \%repeat,
2008     );
2009 }
2010
2011 =head2 GetBorrowersWithEmail
2012
2013     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2014
2015 This gets a list of users and their basic details from their email address.
2016 As it's possible for multiple user to have the same email address, it provides
2017 you with all of them. If there is no userid for the user, there will be an
2018 C<undef> there. An empty list will be returned if there are no matches.
2019
2020 =cut
2021
2022 sub GetBorrowersWithEmail {
2023     my $email = shift;
2024
2025     my $dbh = C4::Context->dbh;
2026
2027     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2028     my $sth=$dbh->prepare($query);
2029     $sth->execute($email);
2030     my @result = ();
2031     while (my $ref = $sth->fetch) {
2032         push @result, $ref;
2033     }
2034     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2035     return @result;
2036 }
2037
2038 =head2 AddMember_Opac
2039
2040 =cut
2041
2042 sub AddMember_Opac {
2043     my ( %borrower ) = @_;
2044
2045     $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2046     if (not defined $borrower{'password'}){
2047         my $sr = new String::Random;
2048         $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2049         my $password = $sr->randpattern("AAAAAAAAAA");
2050         $borrower{'password'} = $password;
2051     }
2052
2053     $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
2054
2055     my $borrowernumber = AddMember(%borrower);
2056
2057     return ( $borrowernumber, $borrower{'password'} );
2058 }
2059
2060 =head2 AddEnrolmentFeeIfNeeded
2061
2062     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2063
2064 Add enrolment fee for a patron if needed.
2065
2066 =cut
2067
2068 sub AddEnrolmentFeeIfNeeded {
2069     my ( $categorycode, $borrowernumber ) = @_;
2070     # check for enrollment fee & add it if needed
2071     my $dbh = C4::Context->dbh;
2072     my $sth = $dbh->prepare(q{
2073         SELECT enrolmentfee
2074         FROM categories
2075         WHERE categorycode=?
2076     });
2077     $sth->execute( $categorycode );
2078     if ( $sth->err ) {
2079         warn sprintf('Database returned the following error: %s', $sth->errstr);
2080         return;
2081     }
2082     my ($enrolmentfee) = $sth->fetchrow;
2083     if ($enrolmentfee && $enrolmentfee > 0) {
2084         # insert fee in patron debts
2085         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2086     }
2087 }
2088
2089 =head2 HasOverdues
2090
2091 =cut
2092
2093 sub HasOverdues {
2094     my ( $borrowernumber ) = @_;
2095
2096     my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2097     my $sth = C4::Context->dbh->prepare( $sql );
2098     $sth->execute( $borrowernumber );
2099     my ( $count ) = $sth->fetchrow_array();
2100
2101     return $count;
2102 }
2103
2104 =head2 DeleteExpiredOpacRegistrations
2105
2106     Delete accounts that haven't been upgraded from the 'temporary' category
2107     Returns the number of removed patrons
2108
2109 =cut
2110
2111 sub DeleteExpiredOpacRegistrations {
2112
2113     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2114     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2115
2116     return 0 if not $category_code or not defined $delay or $delay eq q||;
2117
2118     my $query = qq|
2119 SELECT borrowernumber
2120 FROM borrowers
2121 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2122
2123     my $dbh = C4::Context->dbh;
2124     my $sth = $dbh->prepare($query);
2125     $sth->execute( $category_code, $delay );
2126     my $cnt=0;
2127     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2128         DelMember($borrowernumber);
2129         $cnt++;
2130     }
2131     return $cnt;
2132 }
2133
2134 =head2 DeleteUnverifiedOpacRegistrations
2135
2136     Delete all unverified self registrations in borrower_modifications,
2137     older than the specified number of days.
2138
2139 =cut
2140
2141 sub DeleteUnverifiedOpacRegistrations {
2142     my ( $days ) = @_;
2143     my $dbh = C4::Context->dbh;
2144     my $sql=qq|
2145 DELETE FROM borrower_modifications
2146 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2147     my $cnt=$dbh->do($sql, undef, ($days) );
2148     return $cnt eq '0E0'? 0: $cnt;
2149 }
2150
2151 sub GetOverduesForPatron {
2152     my ( $borrowernumber ) = @_;
2153
2154     my $sql = "
2155         SELECT *
2156         FROM issues, items, biblio, biblioitems
2157         WHERE items.itemnumber=issues.itemnumber
2158           AND biblio.biblionumber   = items.biblionumber
2159           AND biblio.biblionumber   = biblioitems.biblionumber
2160           AND issues.borrowernumber = ?
2161           AND date_due < NOW()
2162     ";
2163
2164     my $sth = C4::Context->dbh->prepare( $sql );
2165     $sth->execute( $borrowernumber );
2166
2167     return $sth->fetchall_arrayref({});
2168 }
2169
2170 END { }    # module clean-up code here (global destructor)
2171
2172 1;
2173
2174 __END__
2175
2176 =head1 AUTHOR
2177
2178 Koha Team
2179
2180 =cut