Bug 16852: Remove GetBorrowerCategorycode
[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 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 use Koha::Patron::Categories;
47
48 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
49
50 use Module::Load::Conditional qw( can_load );
51 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
52    $debug && warn "Unable to load Koha::NorwegianPatronDB";
53 }
54
55
56 BEGIN {
57     $debug = $ENV{DEBUG} || 0;
58     require Exporter;
59     @ISA = qw(Exporter);
60     #Get data
61     push @EXPORT, qw(
62         &Search
63         &GetMemberDetails
64         &GetMember
65
66         &GetMemberIssuesAndFines
67         &GetPendingIssues
68         &GetAllIssues
69
70         &GetFirstValidEmailAddress
71         &GetNoticeEmailAddress
72
73         &GetAge
74         &GetTitles
75
76         &GetHideLostItemsPreference
77
78         &GetMemberAccountRecords
79         &GetBorNotifyAcctRecord
80
81         &GetBorrowersToExpunge
82         &GetBorrowersWhoHaveNeverBorrowed
83         &GetBorrowersWithIssuesHistoryOlderThan
84
85         &GetUpcomingMembershipExpires
86
87         &IssueSlip
88         GetBorrowersWithEmail
89
90         GetOverduesForPatron
91     );
92
93     #Modify data
94     push @EXPORT, qw(
95         &ModMember
96         &changepassword
97     );
98
99     #Insert data
100     push @EXPORT, qw(
101         &AddMember
102         &AddMember_Opac
103     );
104
105     #Check data
106     push @EXPORT, qw(
107         &checkuniquemember
108         &checkuserpassword
109         &Check_Userid
110         &Generate_Userid
111         &fixup_cardnumber
112         &checkcardnumber
113     );
114 }
115
116 =head1 NAME
117
118 C4::Members - Perl Module containing convenience functions for member handling
119
120 =head1 SYNOPSIS
121
122 use C4::Members;
123
124 =head1 DESCRIPTION
125
126 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
127
128 =head1 FUNCTIONS
129
130 =head2 GetMemberDetails
131
132 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
133
134 Looks up a patron and returns information about him or her. If
135 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
136 up the borrower by number; otherwise, it looks up the borrower by card
137 number.
138
139 C<$borrower> is a reference-to-hash whose keys are the fields of the
140 borrowers table in the Koha database. In addition,
141 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
142 about the patron. Its keys act as flags :
143
144     if $borrower->{flags}->{LOST} {
145         # Patron's card was reported lost
146     }
147
148 If the state of a flag means that the patron should not be
149 allowed to borrow any more books, then it will have a C<noissues> key
150 with a true value.
151
152 See patronflags for more details.
153
154 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
155 about the top-level permissions flags set for the borrower.  For example,
156 if a user has the "editcatalogue" permission,
157 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
158 the value "1".
159
160 =cut
161
162 sub GetMemberDetails {
163     my ( $borrowernumber, $cardnumber ) = @_;
164     my $dbh = C4::Context->dbh;
165     my $query;
166     my $sth;
167     if ($borrowernumber) {
168         $sth = $dbh->prepare("
169             SELECT borrowers.*,
170                    category_type,
171                    categories.description,
172                    categories.BlockExpiredPatronOpacActions,
173                    reservefee,
174                    enrolmentperiod
175             FROM borrowers
176             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
177             WHERE borrowernumber = ?
178         ");
179         $sth->execute($borrowernumber);
180     }
181     elsif ($cardnumber) {
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 cardnumber = ?
192         ");
193         $sth->execute($cardnumber);
194     }
195     else {
196         return;
197     }
198     my $borrower = $sth->fetchrow_hashref;
199     return unless $borrower;
200     my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
201     $borrower->{'amountoutstanding'} = $amount;
202     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
203     my $flags = patronflags( $borrower);
204     my $accessflagshash;
205
206     $sth = $dbh->prepare("select bit,flag from userflags");
207     $sth->execute;
208     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
209         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
210             $accessflagshash->{$flag} = 1;
211         }
212     }
213     $borrower->{'flags'}     = $flags;
214     $borrower->{'authflags'} = $accessflagshash;
215
216     # Handle setting the true behavior for BlockExpiredPatronOpacActions
217     $borrower->{'BlockExpiredPatronOpacActions'} =
218       C4::Context->preference('BlockExpiredPatronOpacActions')
219       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
220
221     $borrower->{'is_expired'} = 0;
222     $borrower->{'is_expired'} = 1 if
223       defined($borrower->{dateexpiry}) &&
224       $borrower->{'dateexpiry'} ne '0000-00-00' &&
225       Date_to_Days( Today() ) >
226       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
227
228     return ($borrower);    #, $flags, $accessflagshash);
229 }
230
231 =head2 patronflags
232
233  $flags = &patronflags($patron);
234
235 This function is not exported.
236
237 The following will be set where applicable:
238  $flags->{CHARGES}->{amount}        Amount of debt
239  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
240  $flags->{CHARGES}->{message}       Message -- deprecated
241
242  $flags->{CREDITS}->{amount}        Amount of credit
243  $flags->{CREDITS}->{message}       Message -- deprecated
244
245  $flags->{  GNA  }                  Patron has no valid address
246  $flags->{  GNA  }->{noissues}      Set for each GNA
247  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
248
249  $flags->{ LOST  }                  Patron's card reported lost
250  $flags->{ LOST  }->{noissues}      Set for each LOST
251  $flags->{ LOST  }->{message}       Message -- deprecated
252
253  $flags->{DBARRED}                  Set if patron debarred, no access
254  $flags->{DBARRED}->{noissues}      Set for each DBARRED
255  $flags->{DBARRED}->{message}       Message -- deprecated
256
257  $flags->{ NOTES }
258  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
259
260  $flags->{ ODUES }                  Set if patron has overdue books.
261  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
262  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
263  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
264
265  $flags->{WAITING}                  Set if any of patron's reserves are available
266  $flags->{WAITING}->{message}       Message -- deprecated
267  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
268
269 =over 
270
271 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
272 overdue items. Its elements are references-to-hash, each describing an
273 overdue item. The keys are selected fields from the issues, biblio,
274 biblioitems, and items tables of the Koha database.
275
276 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
277 the overdue items, one per line.  Deprecated.
278
279 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
280 available items. Each element is a reference-to-hash whose keys are
281 fields from the reserves table of the Koha database.
282
283 =back
284
285 All the "message" fields that include language generated in this function are deprecated, 
286 because such strings belong properly in the display layer.
287
288 The "message" field that comes from the DB is OK.
289
290 =cut
291
292 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
293 # FIXME rename this function.
294 sub patronflags {
295     my %flags;
296     my ( $patroninformation) = @_;
297     my $dbh=C4::Context->dbh;
298     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
299     if ( $owing > 0 ) {
300         my %flaginfo;
301         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
302         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
303         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
304         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
305             $flaginfo{'noissues'} = 1;
306         }
307         $flags{'CHARGES'} = \%flaginfo;
308     }
309     elsif ( $balance < 0 ) {
310         my %flaginfo;
311         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
312         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
313         $flags{'CREDITS'} = \%flaginfo;
314     }
315
316     # Check the debt of the guarntees of this patron
317     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
318     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
319     if ( defined $no_issues_charge_guarantees ) {
320         my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
321         my @guarantees = $p->guarantees();
322         my $guarantees_non_issues_charges;
323         foreach my $g ( @guarantees ) {
324             my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
325             $guarantees_non_issues_charges += $n;
326         }
327
328         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
329             my %flaginfo;
330             $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
331             $flaginfo{'amount'}  = $guarantees_non_issues_charges;
332             $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
333             $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
334         }
335     }
336
337     if (   $patroninformation->{'gonenoaddress'}
338         && $patroninformation->{'gonenoaddress'} == 1 )
339     {
340         my %flaginfo;
341         $flaginfo{'message'}  = 'Borrower has no valid address.';
342         $flaginfo{'noissues'} = 1;
343         $flags{'GNA'}         = \%flaginfo;
344     }
345     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
346         my %flaginfo;
347         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
348         $flaginfo{'noissues'} = 1;
349         $flags{'LOST'}        = \%flaginfo;
350     }
351     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
352         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
353             my %flaginfo;
354             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
355             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
356             $flaginfo{'noissues'}        = 1;
357             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
358             $flags{'DBARRED'}           = \%flaginfo;
359         }
360     }
361     if (   $patroninformation->{'borrowernotes'}
362         && $patroninformation->{'borrowernotes'} )
363     {
364         my %flaginfo;
365         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
366         $flags{'NOTES'}      = \%flaginfo;
367     }
368     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
369     if ( $odues && $odues > 0 ) {
370         my %flaginfo;
371         $flaginfo{'message'}  = "Yes";
372         $flaginfo{'itemlist'} = $itemsoverdue;
373         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
374             @$itemsoverdue )
375         {
376             $flaginfo{'itemlisttext'} .=
377               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
378         }
379         $flags{'ODUES'} = \%flaginfo;
380     }
381     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
382     my $nowaiting = scalar @itemswaiting;
383     if ( $nowaiting > 0 ) {
384         my %flaginfo;
385         $flaginfo{'message'}  = "Reserved items available";
386         $flaginfo{'itemlist'} = \@itemswaiting;
387         $flags{'WAITING'}     = \%flaginfo;
388     }
389     return ( \%flags );
390 }
391
392
393 =head2 GetMember
394
395   $borrower = &GetMember(%information);
396
397 Retrieve the first patron record meeting on criteria listed in the
398 C<%information> hash, which should contain one or more
399 pairs of borrowers column names and values, e.g.,
400
401    $borrower = GetMember(borrowernumber => id);
402
403 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
404 the C<borrowers> table in the Koha database.
405
406 FIXME: GetMember() is used throughout the code as a lookup
407 on a unique key such as the borrowernumber, but this meaning is not
408 enforced in the routine itself.
409
410 =cut
411
412 #'
413 sub GetMember {
414     my ( %information ) = @_;
415     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
416         #passing mysql's kohaadmin?? Makes no sense as a query
417         return;
418     }
419     my $dbh = C4::Context->dbh;
420     my $select =
421     q{SELECT borrowers.*, categories.category_type, categories.description
422     FROM borrowers 
423     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
424     my $more_p = 0;
425     my @values = ();
426     for (keys %information ) {
427         if ($more_p) {
428             $select .= ' AND ';
429         }
430         else {
431             $more_p++;
432         }
433
434         if (defined $information{$_}) {
435             $select .= "$_ = ?";
436             push @values, $information{$_};
437         }
438         else {
439             $select .= "$_ IS NULL";
440         }
441     }
442     $debug && warn $select, " ",values %information;
443     my $sth = $dbh->prepare("$select");
444     $sth->execute(@values);
445     my $data = $sth->fetchall_arrayref({});
446     #FIXME interface to this routine now allows generation of a result set
447     #so whole array should be returned but bowhere in the current code expects this
448     if (@{$data} ) {
449         return $data->[0];
450     }
451
452     return;
453 }
454
455 =head2 GetMemberIssuesAndFines
456
457   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
458
459 Returns aggregate data about items borrowed by the patron with the
460 given borrowernumber.
461
462 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
463 number of overdue items the patron currently has borrowed. C<$issue_count> is the
464 number of books the patron currently has borrowed.  C<$total_fines> is
465 the total fine currently due by the borrower.
466
467 =cut
468
469 #'
470 sub GetMemberIssuesAndFines {
471     my ( $borrowernumber ) = @_;
472     my $dbh   = C4::Context->dbh;
473     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
474
475     $debug and warn $query."\n";
476     my $sth = $dbh->prepare($query);
477     $sth->execute($borrowernumber);
478     my $issue_count = $sth->fetchrow_arrayref->[0];
479
480     $sth = $dbh->prepare(
481         "SELECT COUNT(*) FROM issues 
482          WHERE borrowernumber = ? 
483          AND date_due < now()"
484     );
485     $sth->execute($borrowernumber);
486     my $overdue_count = $sth->fetchrow_arrayref->[0];
487
488     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
489     $sth->execute($borrowernumber);
490     my $total_fines = $sth->fetchrow_arrayref->[0];
491
492     return ($overdue_count, $issue_count, $total_fines);
493 }
494
495
496 =head2 ModMember
497
498   my $success = ModMember(borrowernumber => $borrowernumber,
499                                             [ field => value ]... );
500
501 Modify borrower's data.  All date fields should ALREADY be in ISO format.
502
503 return :
504 true on success, or false on failure
505
506 =cut
507
508 sub ModMember {
509     my (%data) = @_;
510     # test to know if you must update or not the borrower password
511     if (exists $data{password}) {
512         if ($data{password} eq '****' or $data{password} eq '') {
513             delete $data{password};
514         } else {
515             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
516                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
517                 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
518             }
519             $data{password} = hash_password($data{password});
520         }
521     }
522
523     my $old_categorycode = Koha::Patrons->find( $data{borrowernumber} )->categorycode;
524
525     # get only the columns of a borrower
526     my $schema = Koha::Database->new()->schema;
527     my @columns = $schema->source('Borrower')->columns;
528     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
529     delete $new_borrower->{flags};
530
531     $new_borrower->{dateofbirth}     ||= undef if exists $new_borrower->{dateofbirth};
532     $new_borrower->{dateenrolled}    ||= undef if exists $new_borrower->{dateenrolled};
533     $new_borrower->{dateexpiry}      ||= undef if exists $new_borrower->{dateexpiry};
534     $new_borrower->{debarred}        ||= undef if exists $new_borrower->{debarred};
535     $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
536     $new_borrower->{guarantorid}     ||= undef if exists $new_borrower->{guarantorid};
537
538     my $patron = Koha::Patrons->find( $new_borrower->{borrowernumber} );
539
540     delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
541
542     my $execute_success = $patron->store if $patron->set($new_borrower);
543
544     if ($execute_success) { # only proceed if the update was a success
545         # If the patron changes to a category with enrollment fee, we add a fee
546         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
547             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
548                 $patron->add_enrolment_fee_if_needed;
549             }
550         }
551
552         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
553         # cronjob will use for syncing with NL
554         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
555             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
556                 'synctype'       => 'norwegianpatrondb',
557                 'borrowernumber' => $data{'borrowernumber'}
558             });
559             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
560             # we can sync as changed. And the "new sync" will pick up all changes since
561             # the patron was created anyway.
562             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
563                 $borrowersync->update( { 'syncstatus' => 'edited' } );
564             }
565             # Set the value of 'sync'
566             $borrowersync->update( { 'sync' => $data{'sync'} } );
567             # Try to do the live sync
568             Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
569         }
570
571         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
572     }
573     return $execute_success;
574 }
575
576 =head2 AddMember
577
578   $borrowernumber = &AddMember(%borrower);
579
580 insert new borrower into table
581
582 (%borrower keys are database columns. Database columns could be
583 different in different versions. Please look into database for correct
584 column names.)
585
586 Returns the borrowernumber upon success
587
588 Returns as undef upon any db error without further processing
589
590 =cut
591
592 #'
593 sub AddMember {
594     my (%data) = @_;
595     my $dbh = C4::Context->dbh;
596     my $schema = Koha::Database->new()->schema;
597
598     # generate a proper login if none provided
599     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
600       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
601
602     # add expiration date if it isn't already there
603     $data{dateexpiry} ||= Koha::Patron::Categories->find( $data{categorycode} )->get_expiry_date;
604
605     # add enrollment date if it isn't already there
606     unless ( $data{'dateenrolled'} ) {
607         $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
608     }
609
610     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
611     $data{'privacy'} =
612         $patron_category->default_privacy() eq 'default' ? 1
613       : $patron_category->default_privacy() eq 'never'   ? 2
614       : $patron_category->default_privacy() eq 'forever' ? 0
615       :                                                    undef;
616
617     $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
618
619     # Make a copy of the plain text password for later use
620     my $plain_text_password = $data{'password'};
621
622     # create a disabled account if no password provided
623     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
624
625     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
626     $data{'dateofbirth'}     = undef if ( not $data{'dateofbirth'} );
627     $data{'debarred'}        = undef if ( not $data{'debarred'} );
628     $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
629
630     # get only the columns of Borrower
631     # FIXME Do we really need this check?
632     my @columns = $schema->source('Borrower')->columns;
633     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
634
635     delete $new_member->{borrowernumber};
636
637     my $patron = Koha::Patron->new( $new_member )->store;
638     $data{borrowernumber} = $patron->borrowernumber;
639
640     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
641     # cronjob will use for syncing with NL
642     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
643         Koha::Database->new->schema->resultset('BorrowerSync')->create({
644             'borrowernumber' => $data{'borrowernumber'},
645             'synctype'       => 'norwegianpatrondb',
646             'sync'           => 1,
647             'syncstatus'     => 'new',
648             'hashed_pin'     => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
649         });
650     }
651
652     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
653
654     $patron->add_enrolment_fee_if_needed;
655
656     return $data{borrowernumber};
657 }
658
659 =head2 Check_Userid
660
661     my $uniqueness = Check_Userid($userid,$borrowernumber);
662
663     $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
664
665     If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
666
667     return :
668         0 for not unique (i.e. this $userid already exists)
669         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
670
671 =cut
672
673 sub Check_Userid {
674     my ( $uid, $borrowernumber ) = @_;
675
676     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
677
678     return 0 if ( $uid eq C4::Context->config('user') );
679
680     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
681
682     my $params;
683     $params->{userid} = $uid;
684     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
685
686     my $count = $rs->count( $params );
687
688     return $count ? 0 : 1;
689 }
690
691 =head2 Generate_Userid
692
693     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
694
695     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
696
697     $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
698
699     return :
700         new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
701
702 =cut
703
704 sub Generate_Userid {
705   my ($borrowernumber, $firstname, $surname) = @_;
706   my $newuid;
707   my $offset = 0;
708   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
709   do {
710     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
711     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
712     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
713     $newuid = unac_string('utf-8',$newuid);
714     $newuid .= $offset unless $offset == 0;
715     $offset++;
716
717    } while (!Check_Userid($newuid,$borrowernumber));
718
719    return $newuid;
720 }
721
722 =head2 fixup_cardnumber
723
724 Warning: The caller is responsible for locking the members table in write
725 mode, to avoid database corruption.
726
727 =cut
728
729 use vars qw( @weightings );
730 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
731
732 sub fixup_cardnumber {
733     my ($cardnumber) = @_;
734     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
735
736     # Find out whether member numbers should be generated
737     # automatically. Should be either "1" or something else.
738     # Defaults to "0", which is interpreted as "no".
739
740     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
741     ($autonumber_members) or return $cardnumber;
742     my $checkdigit = C4::Context->preference('checkdigit');
743     my $dbh = C4::Context->dbh;
744     if ( $checkdigit and $checkdigit eq 'katipo' ) {
745
746         # if checkdigit is selected, calculate katipo-style cardnumber.
747         # otherwise, just use the max()
748         # purpose: generate checksum'd member numbers.
749         # We'll assume we just got the max value of digits 2-8 of member #'s
750         # from the database and our job is to increment that by one,
751         # determine the 1st and 9th digits and return the full string.
752         my $sth = $dbh->prepare(
753             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
754         );
755         $sth->execute;
756         my $data = $sth->fetchrow_hashref;
757         $cardnumber = $data->{new_num};
758         if ( !$cardnumber ) {    # If DB has no values,
759             $cardnumber = 1000000;    # start at 1000000
760         } else {
761             $cardnumber += 1;
762         }
763
764         my $sum = 0;
765         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
766             # read weightings, left to right, 1 char at a time
767             my $temp1 = $weightings[$i];
768
769             # sequence left to right, 1 char at a time
770             my $temp2 = substr( $cardnumber, $i, 1 );
771
772             # mult each char 1-7 by its corresponding weighting
773             $sum += $temp1 * $temp2;
774         }
775
776         my $rem = ( $sum % 11 );
777         $rem = 'X' if $rem == 10;
778
779         return "V$cardnumber$rem";
780      } else {
781
782         my $sth = $dbh->prepare(
783             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
784         );
785         $sth->execute;
786         my ($result) = $sth->fetchrow;
787         return $result + 1;
788     }
789     return $cardnumber;     # just here as a fallback/reminder 
790 }
791
792 =head2 GetPendingIssues
793
794   my $issues = &GetPendingIssues(@borrowernumber);
795
796 Looks up what the patron with the given borrowernumber has borrowed.
797
798 C<&GetPendingIssues> returns a
799 reference-to-array where each element is a reference-to-hash; the
800 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
801 The keys include C<biblioitems> fields except marc and marcxml.
802
803 =cut
804
805 sub GetPendingIssues {
806     my @borrowernumbers = @_;
807
808     unless (@borrowernumbers ) { # return a ref_to_array
809         return \@borrowernumbers; # to not cause surprise to caller
810     }
811
812     # Borrowers part of the query
813     my $bquery = '';
814     for (my $i = 0; $i < @borrowernumbers; $i++) {
815         $bquery .= ' issues.borrowernumber = ?';
816         if ($i < $#borrowernumbers ) {
817             $bquery .= ' OR';
818         }
819     }
820
821     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
822     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
823     # FIXME: circ/ciculation.pl tries to sort by timestamp!
824     # FIXME: namespace collision: other collisions possible.
825     # FIXME: most of this data isn't really being used by callers.
826     my $query =
827    "SELECT issues.*,
828             items.*,
829            biblio.*,
830            biblioitems.volume,
831            biblioitems.number,
832            biblioitems.itemtype,
833            biblioitems.isbn,
834            biblioitems.issn,
835            biblioitems.publicationyear,
836            biblioitems.publishercode,
837            biblioitems.volumedate,
838            biblioitems.volumedesc,
839            biblioitems.lccn,
840            biblioitems.url,
841            borrowers.firstname,
842            borrowers.surname,
843            borrowers.cardnumber,
844            issues.timestamp AS timestamp,
845            issues.renewals  AS renewals,
846            issues.borrowernumber AS borrowernumber,
847             items.renewals  AS totalrenewals
848     FROM   issues
849     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
850     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
851     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
852     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
853     WHERE
854       $bquery
855     ORDER BY issues.issuedate"
856     ;
857
858     my $sth = C4::Context->dbh->prepare($query);
859     $sth->execute(@borrowernumbers);
860     my $data = $sth->fetchall_arrayref({});
861     my $today = dt_from_string;
862     foreach (@{$data}) {
863         if ($_->{issuedate}) {
864             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
865         }
866         $_->{date_due_sql} = $_->{date_due};
867         # FIXME no need to have this value
868         $_->{date_due} or next;
869         $_->{date_due_sql} = $_->{date_due};
870         # FIXME no need to have this value
871         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
872         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
873             $_->{overdue} = 1;
874         }
875     }
876     return $data;
877 }
878
879 =head2 GetAllIssues
880
881   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
882
883 Looks up what the patron with the given borrowernumber has borrowed,
884 and sorts the results.
885
886 C<$sortkey> is the name of a field on which to sort the results. This
887 should be the name of a field in the C<issues>, C<biblio>,
888 C<biblioitems>, or C<items> table in the Koha database.
889
890 C<$limit> is the maximum number of results to return.
891
892 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
893 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
894 C<items> tables of the Koha database.
895
896 =cut
897
898 #'
899 sub GetAllIssues {
900     my ( $borrowernumber, $order, $limit ) = @_;
901
902     return unless $borrowernumber;
903     $order = 'date_due desc' unless $order;
904
905     my $dbh = C4::Context->dbh;
906     my $query =
907 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
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   WHERE borrowernumber=? 
913   UNION ALL
914   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
915   FROM old_issues 
916   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
917   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
918   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
919   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
920   order by ' . $order;
921     if ($limit) {
922         $query .= " limit $limit";
923     }
924
925     my $sth = $dbh->prepare($query);
926     $sth->execute( $borrowernumber, $borrowernumber );
927     return $sth->fetchall_arrayref( {} );
928 }
929
930
931 =head2 GetMemberAccountRecords
932
933   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
934
935 Looks up accounting data for the patron with the given borrowernumber.
936
937 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
938 reference-to-array, where each element is a reference-to-hash; the
939 keys are the fields of the C<accountlines> table in the Koha database.
940 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
941 total amount outstanding for all of the account lines.
942
943 =cut
944
945 sub GetMemberAccountRecords {
946     my ($borrowernumber) = @_;
947     my $dbh = C4::Context->dbh;
948     my @acctlines;
949     my $numlines = 0;
950     my $strsth      = qq(
951                         SELECT * 
952                         FROM accountlines 
953                         WHERE borrowernumber=?);
954     $strsth.=" ORDER BY accountlines_id desc";
955     my $sth= $dbh->prepare( $strsth );
956     $sth->execute( $borrowernumber );
957
958     my $total = 0;
959     while ( my $data = $sth->fetchrow_hashref ) {
960         if ( $data->{itemnumber} ) {
961             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
962             $data->{biblionumber} = $biblio->{biblionumber};
963             $data->{title}        = $biblio->{title};
964         }
965         $acctlines[$numlines] = $data;
966         $numlines++;
967         $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
968     }
969     $total /= 1000;
970     return ( $total, \@acctlines,$numlines);
971 }
972
973 =head2 GetMemberAccountBalance
974
975   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
976
977 Calculates amount immediately owing by the patron - non-issue charges.
978 Based on GetMemberAccountRecords.
979 Charges exempt from non-issue are:
980 * Res (reserves)
981 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
982 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
983
984 =cut
985
986 sub GetMemberAccountBalance {
987     my ($borrowernumber) = @_;
988
989     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
990
991     my @not_fines;
992     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
993     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
994     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
995         my $dbh = C4::Context->dbh;
996         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
997         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
998     }
999     my %not_fine = map {$_ => 1} @not_fines;
1000
1001     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1002     my $other_charges = 0;
1003     foreach (@$acctlines) {
1004         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1005     }
1006
1007     return ( $total, $total - $other_charges, $other_charges);
1008 }
1009
1010 =head2 GetBorNotifyAcctRecord
1011
1012   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1013
1014 Looks up accounting data for the patron with the given borrowernumber per file number.
1015
1016 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1017 reference-to-array, where each element is a reference-to-hash; the
1018 keys are the fields of the C<accountlines> table in the Koha database.
1019 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1020 total amount outstanding for all of the account lines.
1021
1022 =cut
1023
1024 sub GetBorNotifyAcctRecord {
1025     my ( $borrowernumber, $notifyid ) = @_;
1026     my $dbh = C4::Context->dbh;
1027     my @acctlines;
1028     my $numlines = 0;
1029     my $sth = $dbh->prepare(
1030             "SELECT * 
1031                 FROM accountlines 
1032                 WHERE borrowernumber=? 
1033                     AND notify_id=? 
1034                     AND amountoutstanding != '0' 
1035                 ORDER BY notify_id,accounttype
1036                 ");
1037
1038     $sth->execute( $borrowernumber, $notifyid );
1039     my $total = 0;
1040     while ( my $data = $sth->fetchrow_hashref ) {
1041         if ( $data->{itemnumber} ) {
1042             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1043             $data->{biblionumber} = $biblio->{biblionumber};
1044             $data->{title}        = $biblio->{title};
1045         }
1046         $acctlines[$numlines] = $data;
1047         $numlines++;
1048         $total += int(100 * $data->{'amountoutstanding'});
1049     }
1050     $total /= 100;
1051     return ( $total, \@acctlines, $numlines );
1052 }
1053
1054 sub checkcardnumber {
1055     my ( $cardnumber, $borrowernumber ) = @_;
1056
1057     # If cardnumber is null, we assume they're allowed.
1058     return 0 unless defined $cardnumber;
1059
1060     my $dbh = C4::Context->dbh;
1061     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1062     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1063     my $sth = $dbh->prepare($query);
1064     $sth->execute(
1065         $cardnumber,
1066         ( $borrowernumber ? $borrowernumber : () )
1067     );
1068
1069     return 1 if $sth->fetchrow_hashref;
1070
1071     my ( $min_length, $max_length ) = get_cardnumber_length();
1072     return 2
1073         if length $cardnumber > $max_length
1074         or length $cardnumber < $min_length;
1075
1076     return 0;
1077 }
1078
1079 =head2 get_cardnumber_length
1080
1081     my ($min, $max) = C4::Members::get_cardnumber_length()
1082
1083 Returns the minimum and maximum length for patron cardnumbers as
1084 determined by the CardnumberLength system preference, the
1085 BorrowerMandatoryField system preference, and the width of the
1086 database column.
1087
1088 =cut
1089
1090 sub get_cardnumber_length {
1091     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1092     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1093     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1094         # Is integer and length match
1095         if ( $cardnumber_length =~ m|^\d+$| ) {
1096             $min = $max = $cardnumber_length
1097                 if $cardnumber_length >= $min
1098                     and $cardnumber_length <= $max;
1099         }
1100         # Else assuming it is a range
1101         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1102             $min = $1 if $1 and $min < $1;
1103             $max = $2 if $2 and $max > $2;
1104         }
1105
1106     }
1107     return ( $min, $max );
1108 }
1109
1110 =head2 GetFirstValidEmailAddress
1111
1112   $email = GetFirstValidEmailAddress($borrowernumber);
1113
1114 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1115 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1116 addresses.
1117
1118 =cut
1119
1120 sub GetFirstValidEmailAddress {
1121     my $borrowernumber = shift;
1122     my $dbh = C4::Context->dbh;
1123     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1124     $sth->execute( $borrowernumber );
1125     my $data = $sth->fetchrow_hashref;
1126
1127     if ($data->{'email'}) {
1128        return $data->{'email'};
1129     } elsif ($data->{'emailpro'}) {
1130        return $data->{'emailpro'};
1131     } elsif ($data->{'B_email'}) {
1132        return $data->{'B_email'};
1133     } else {
1134        return '';
1135     }
1136 }
1137
1138 =head2 GetNoticeEmailAddress
1139
1140   $email = GetNoticeEmailAddress($borrowernumber);
1141
1142 Return the email address of borrower used for notices, given the borrowernumber.
1143 Returns the empty string if no email address.
1144
1145 =cut
1146
1147 sub GetNoticeEmailAddress {
1148     my $borrowernumber = shift;
1149
1150     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1151     # if syspref is set to 'first valid' (value == OFF), look up email address
1152     if ( $which_address eq 'OFF' ) {
1153         return GetFirstValidEmailAddress($borrowernumber);
1154     }
1155     # specified email address field
1156     my $dbh = C4::Context->dbh;
1157     my $sth = $dbh->prepare( qq{
1158         SELECT $which_address AS primaryemail
1159         FROM borrowers
1160         WHERE borrowernumber=?
1161     } );
1162     $sth->execute($borrowernumber);
1163     my $data = $sth->fetchrow_hashref;
1164     return $data->{'primaryemail'} || '';
1165 }
1166
1167 =head2 GetUpcomingMembershipExpires
1168
1169     my $expires = GetUpcomingMembershipExpires({
1170         branch => $branch, before => $before, after => $after,
1171     });
1172
1173     $branch is an optional branch code.
1174     $before/$after is an optional number of days before/after the date that
1175     is set by the preference MembershipExpiryDaysNotice.
1176     If the pref would be 14, before 2 and after 3, you will get all expires
1177     from 12 to 17 days.
1178
1179 =cut
1180
1181 sub GetUpcomingMembershipExpires {
1182     my ( $params ) = @_;
1183     my $before = $params->{before} || 0;
1184     my $after  = $params->{after} || 0;
1185     my $branch = $params->{branch};
1186
1187     my $dbh = C4::Context->dbh;
1188     my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1189     my $date1 = dt_from_string->add( days => $days - $before );
1190     my $date2 = dt_from_string->add( days => $days + $after );
1191     $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1192     $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1193
1194     my $query = q|
1195         SELECT borrowers.*, categories.description,
1196         branches.branchname, branches.branchemail FROM borrowers
1197         LEFT JOIN branches USING (branchcode)
1198         LEFT JOIN categories USING (categorycode)
1199     |;
1200     if( $branch ) {
1201         $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1202     } else {
1203         $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1204     }
1205
1206     my $sth = $dbh->prepare( $query );
1207     my @pars = $branch? ( $branch ): ();
1208     push @pars, $date1, $date2;
1209     $sth->execute( @pars );
1210     my $results = $sth->fetchall_arrayref( {} );
1211     return $results;
1212 }
1213
1214 =head2 GetAge
1215
1216   $dateofbirth,$date = &GetAge($date);
1217
1218 this function return the borrowers age with the value of dateofbirth
1219
1220 =cut
1221
1222 #'
1223 sub GetAge{
1224     my ( $date, $date_ref ) = @_;
1225
1226     if ( not defined $date_ref ) {
1227         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1228     }
1229
1230     my ( $year1, $month1, $day1 ) = split /-/, $date;
1231     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1232
1233     my $age = $year2 - $year1;
1234     if ( $month1 . $day1 > $month2 . $day2 ) {
1235         $age--;
1236     }
1237
1238     return $age;
1239 }    # sub get_age
1240
1241 =head2 SetAge
1242
1243   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1244   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1245   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1246
1247   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1248   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1249
1250 This function sets the borrower's dateofbirth to match the given age.
1251 Optionally relative to the given $datetime_reference.
1252
1253 @PARAM1 koha.borrowers-object
1254 @PARAM2 DateTime::Duration-object as the desired age
1255         OR a ISO 8601 Date. (To make the API more pleasant)
1256 @PARAM3 DateTime-object as the relative date, defaults to now().
1257 RETURNS The given borrower reference @PARAM1.
1258 DIES    If there was an error with the ISO Date handling.
1259
1260 =cut
1261
1262 #'
1263 sub SetAge{
1264     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1265     $datetime_ref = DateTime->now() unless $datetime_ref;
1266
1267     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1268         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1269             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1270         }
1271         else {
1272             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1273         }
1274     }
1275
1276     my $new_datetime_ref = $datetime_ref->clone();
1277     $new_datetime_ref->subtract_duration( $datetimeduration );
1278
1279     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1280
1281     return $borrower;
1282 }    # sub SetAge
1283
1284 =head2 GetHideLostItemsPreference
1285
1286   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1287
1288 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1289 C<&$hidelostitemspref>return value of function, 0 or 1
1290
1291 =cut
1292
1293 sub GetHideLostItemsPreference {
1294     my ($borrowernumber) = @_;
1295     my $dbh = C4::Context->dbh;
1296     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1297     my $sth = $dbh->prepare($query);
1298     $sth->execute($borrowernumber);
1299     my $hidelostitems = $sth->fetchrow;    
1300     return $hidelostitems;    
1301 }
1302
1303 =head2 GetBorrowersToExpunge
1304
1305   $borrowers = &GetBorrowersToExpunge(
1306       not_borrowed_since => $not_borrowed_since,
1307       expired_before       => $expired_before,
1308       category_code        => $category_code,
1309       patron_list_id       => $patron_list_id,
1310       branchcode           => $branchcode
1311   );
1312
1313   This function get all borrowers based on the given criteria.
1314
1315 =cut
1316
1317 sub GetBorrowersToExpunge {
1318
1319     my $params = shift;
1320     my $filterdate       = $params->{'not_borrowed_since'};
1321     my $filterexpiry     = $params->{'expired_before'};
1322     my $filterlastseen   = $params->{'last_seen'};
1323     my $filtercategory   = $params->{'category_code'};
1324     my $filterbranch     = $params->{'branchcode'} ||
1325                         ((C4::Context->preference('IndependentBranches')
1326                              && C4::Context->userenv 
1327                              && !C4::Context->IsSuperLibrarian()
1328                              && C4::Context->userenv->{branch})
1329                          ? C4::Context->userenv->{branch}
1330                          : "");  
1331     my $filterpatronlist = $params->{'patron_list_id'};
1332
1333     my $dbh   = C4::Context->dbh;
1334     my $query = q|
1335         SELECT borrowers.borrowernumber,
1336                MAX(old_issues.timestamp) AS latestissue,
1337                MAX(issues.timestamp) AS currentissue
1338         FROM   borrowers
1339         JOIN   categories USING (categorycode)
1340         LEFT JOIN (
1341             SELECT guarantorid
1342             FROM borrowers
1343             WHERE guarantorid IS NOT NULL
1344                 AND guarantorid <> 0
1345         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1346         LEFT JOIN old_issues USING (borrowernumber)
1347         LEFT JOIN issues USING (borrowernumber)|;
1348     if ( $filterpatronlist  ){
1349         $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1350     }
1351     $query .= q| WHERE  category_type <> 'S'
1352         AND tmp.guarantorid IS NULL
1353    |;
1354     my @query_params;
1355     if ( $filterbranch && $filterbranch ne "" ) {
1356         $query.= " AND borrowers.branchcode = ? ";
1357         push( @query_params, $filterbranch );
1358     }
1359     if ( $filterexpiry ) {
1360         $query .= " AND dateexpiry < ? ";
1361         push( @query_params, $filterexpiry );
1362     }
1363     if ( $filterlastseen ) {
1364         $query .= ' AND lastseen < ? ';
1365         push @query_params, $filterlastseen;
1366     }
1367     if ( $filtercategory ) {
1368         $query .= " AND categorycode = ? ";
1369         push( @query_params, $filtercategory );
1370     }
1371     if ( $filterpatronlist ){
1372         $query.=" AND patron_list_id = ? ";
1373         push( @query_params, $filterpatronlist );
1374     }
1375     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1376     if ( $filterdate ) {
1377         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1378         push @query_params,$filterdate;
1379     }
1380     warn $query if $debug;
1381
1382     my $sth = $dbh->prepare($query);
1383     if (scalar(@query_params)>0){  
1384         $sth->execute(@query_params);
1385     }
1386     else {
1387         $sth->execute;
1388     }
1389     
1390     my @results;
1391     while ( my $data = $sth->fetchrow_hashref ) {
1392         push @results, $data;
1393     }
1394     return \@results;
1395 }
1396
1397 =head2 GetBorrowersWhoHaveNeverBorrowed
1398
1399   $results = &GetBorrowersWhoHaveNeverBorrowed
1400
1401 This function get all borrowers who have never borrowed.
1402
1403 I<$result> is a ref to an array which all elements are a hasref.
1404
1405 =cut
1406
1407 sub GetBorrowersWhoHaveNeverBorrowed {
1408     my $filterbranch = shift || 
1409                         ((C4::Context->preference('IndependentBranches')
1410                              && C4::Context->userenv 
1411                              && !C4::Context->IsSuperLibrarian()
1412                              && C4::Context->userenv->{branch})
1413                          ? C4::Context->userenv->{branch}
1414                          : "");  
1415     my $dbh   = C4::Context->dbh;
1416     my $query = "
1417         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1418         FROM   borrowers
1419           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1420         WHERE issues.borrowernumber IS NULL
1421    ";
1422     my @query_params;
1423     if ($filterbranch && $filterbranch ne ""){ 
1424         $query.=" AND borrowers.branchcode= ?";
1425         push @query_params,$filterbranch;
1426     }
1427     warn $query if $debug;
1428   
1429     my $sth = $dbh->prepare($query);
1430     if (scalar(@query_params)>0){  
1431         $sth->execute(@query_params);
1432     } 
1433     else {
1434         $sth->execute;
1435     }      
1436     
1437     my @results;
1438     while ( my $data = $sth->fetchrow_hashref ) {
1439         push @results, $data;
1440     }
1441     return \@results;
1442 }
1443
1444 =head2 GetBorrowersWithIssuesHistoryOlderThan
1445
1446   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1447
1448 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1449
1450 I<$result> is a ref to an array which all elements are a hashref.
1451 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1452
1453 =cut
1454
1455 sub GetBorrowersWithIssuesHistoryOlderThan {
1456     my $dbh  = C4::Context->dbh;
1457     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1458     my $filterbranch = shift || 
1459                         ((C4::Context->preference('IndependentBranches')
1460                              && C4::Context->userenv 
1461                              && !C4::Context->IsSuperLibrarian()
1462                              && C4::Context->userenv->{branch})
1463                          ? C4::Context->userenv->{branch}
1464                          : "");  
1465     my $query = "
1466        SELECT count(borrowernumber) as n,borrowernumber
1467        FROM old_issues
1468        WHERE returndate < ?
1469          AND borrowernumber IS NOT NULL 
1470     "; 
1471     my @query_params;
1472     push @query_params, $date;
1473     if ($filterbranch){
1474         $query.="   AND branchcode = ?";
1475         push @query_params, $filterbranch;
1476     }    
1477     $query.=" GROUP BY borrowernumber ";
1478     warn $query if $debug;
1479     my $sth = $dbh->prepare($query);
1480     $sth->execute(@query_params);
1481     my @results;
1482
1483     while ( my $data = $sth->fetchrow_hashref ) {
1484         push @results, $data;
1485     }
1486     return \@results;
1487 }
1488
1489 =head2 IssueSlip
1490
1491   IssueSlip($branchcode, $borrowernumber, $quickslip)
1492
1493   Returns letter hash ( see C4::Letters::GetPreparedLetter )
1494
1495   $quickslip is boolean, to indicate whether we want a quick slip
1496
1497   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1498
1499   Both slips:
1500
1501       <<branches.*>>
1502       <<borrowers.*>>
1503
1504   ISSUESLIP:
1505
1506       <checkedout>
1507          <<biblio.*>>
1508          <<items.*>>
1509          <<biblioitems.*>>
1510          <<issues.*>>
1511       </checkedout>
1512
1513       <overdue>
1514          <<biblio.*>>
1515          <<items.*>>
1516          <<biblioitems.*>>
1517          <<issues.*>>
1518       </overdue>
1519
1520       <news>
1521          <<opac_news.*>>
1522       </news>
1523
1524   ISSUEQSLIP:
1525
1526       <checkedout>
1527          <<biblio.*>>
1528          <<items.*>>
1529          <<biblioitems.*>>
1530          <<issues.*>>
1531       </checkedout>
1532
1533   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1534
1535 =cut
1536
1537 sub IssueSlip {
1538     my ($branch, $borrowernumber, $quickslip) = @_;
1539
1540     # FIXME Check callers before removing this statement
1541     #return unless $borrowernumber;
1542
1543     my @issues = @{ GetPendingIssues($borrowernumber) };
1544
1545     for my $issue (@issues) {
1546         $issue->{date_due} = $issue->{date_due_sql};
1547         if ($quickslip) {
1548             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1549             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1550                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1551                   $issue->{now} = 1;
1552             };
1553         }
1554     }
1555
1556     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1557     @issues = sort {
1558         my $s = $b->{timestamp} <=> $a->{timestamp};
1559         $s == 0 ?
1560              $b->{issuedate} <=> $a->{issuedate} : $s;
1561     } @issues;
1562
1563     my ($letter_code, %repeat);
1564     if ( $quickslip ) {
1565         $letter_code = 'ISSUEQSLIP';
1566         %repeat =  (
1567             'checkedout' => [ map {
1568                 'biblio'       => $_,
1569                 'items'        => $_,
1570                 'biblioitems'  => $_,
1571                 'issues'       => $_,
1572             }, grep { $_->{'now'} } @issues ],
1573         );
1574     }
1575     else {
1576         $letter_code = 'ISSUESLIP';
1577         %repeat =  (
1578             'checkedout' => [ map {
1579                 'biblio'       => $_,
1580                 'items'        => $_,
1581                 'biblioitems'  => $_,
1582                 'issues'       => $_,
1583             }, grep { !$_->{'overdue'} } @issues ],
1584
1585             'overdue' => [ map {
1586                 'biblio'       => $_,
1587                 'items'        => $_,
1588                 'biblioitems'  => $_,
1589                 'issues'       => $_,
1590             }, grep { $_->{'overdue'} } @issues ],
1591
1592             'news' => [ map {
1593                 $_->{'timestamp'} = $_->{'newdate'};
1594                 { opac_news => $_ }
1595             } @{ GetNewsToDisplay("slip",$branch) } ],
1596         );
1597     }
1598
1599     return  C4::Letters::GetPreparedLetter (
1600         module => 'circulation',
1601         letter_code => $letter_code,
1602         branchcode => $branch,
1603         tables => {
1604             'branches'    => $branch,
1605             'borrowers'   => $borrowernumber,
1606         },
1607         repeat => \%repeat,
1608     );
1609 }
1610
1611 =head2 GetBorrowersWithEmail
1612
1613     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
1614
1615 This gets a list of users and their basic details from their email address.
1616 As it's possible for multiple user to have the same email address, it provides
1617 you with all of them. If there is no userid for the user, there will be an
1618 C<undef> there. An empty list will be returned if there are no matches.
1619
1620 =cut
1621
1622 sub GetBorrowersWithEmail {
1623     my $email = shift;
1624
1625     my $dbh = C4::Context->dbh;
1626
1627     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
1628     my $sth=$dbh->prepare($query);
1629     $sth->execute($email);
1630     my @result = ();
1631     while (my $ref = $sth->fetch) {
1632         push @result, $ref;
1633     }
1634     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
1635     return @result;
1636 }
1637
1638 =head2 AddMember_Opac
1639
1640 =cut
1641
1642 sub AddMember_Opac {
1643     my ( %borrower ) = @_;
1644
1645     $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1646     if (not defined $borrower{'password'}){
1647         my $sr = new String::Random;
1648         $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1649         my $password = $sr->randpattern("AAAAAAAAAA");
1650         $borrower{'password'} = $password;
1651     }
1652
1653     $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
1654
1655     my $borrowernumber = AddMember(%borrower);
1656
1657     return ( $borrowernumber, $borrower{'password'} );
1658 }
1659
1660 =head2 DeleteExpiredOpacRegistrations
1661
1662     Delete accounts that haven't been upgraded from the 'temporary' category
1663     Returns the number of removed patrons
1664
1665 =cut
1666
1667 sub DeleteExpiredOpacRegistrations {
1668
1669     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1670     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1671
1672     return 0 if not $category_code or not defined $delay or $delay eq q||;
1673
1674     my $query = qq|
1675 SELECT borrowernumber
1676 FROM borrowers
1677 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
1678
1679     my $dbh = C4::Context->dbh;
1680     my $sth = $dbh->prepare($query);
1681     $sth->execute( $category_code, $delay );
1682     my $cnt=0;
1683     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1684         Koha::Patrons->find($borrowernumber)->delete;
1685         $cnt++;
1686     }
1687     return $cnt;
1688 }
1689
1690 =head2 DeleteUnverifiedOpacRegistrations
1691
1692     Delete all unverified self registrations in borrower_modifications,
1693     older than the specified number of days.
1694
1695 =cut
1696
1697 sub DeleteUnverifiedOpacRegistrations {
1698     my ( $days ) = @_;
1699     my $dbh = C4::Context->dbh;
1700     my $sql=qq|
1701 DELETE FROM borrower_modifications
1702 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
1703     my $cnt=$dbh->do($sql, undef, ($days) );
1704     return $cnt eq '0E0'? 0: $cnt;
1705 }
1706
1707 sub GetOverduesForPatron {
1708     my ( $borrowernumber ) = @_;
1709
1710     my $sql = "
1711         SELECT *
1712         FROM issues, items, biblio, biblioitems
1713         WHERE items.itemnumber=issues.itemnumber
1714           AND biblio.biblionumber   = items.biblionumber
1715           AND biblio.biblionumber   = biblioitems.biblionumber
1716           AND issues.borrowernumber = ?
1717           AND date_due < NOW()
1718     ";
1719
1720     my $sth = C4::Context->dbh->prepare( $sql );
1721     $sth->execute( $borrowernumber );
1722
1723     return $sth->fetchall_arrayref({});
1724 }
1725
1726 END { }    # module clean-up code here (global destructor)
1727
1728 1;
1729
1730 __END__
1731
1732 =head1 AUTHOR
1733
1734 Koha Team
1735
1736 =cut