Bug 19025: Move GetReserveInfo to Koha::Holds
[koha.git] / members / memberentry.pl
blobc58b2a9bff62b570fcc1268e9c137df3ee7f5293
1 #!/usr/bin/perl
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 # pragma
22 use strict;
23 use warnings;
25 # external modules
26 use CGI qw ( -utf8 );
27 use List::MoreUtils qw/uniq/;
29 # internal modules
30 use C4::Auth;
31 use C4::Context;
32 use C4::Output;
33 use C4::Members;
34 use C4::Members::Attributes;
35 use C4::Members::AttributeTypes;
36 use C4::Koha;
37 use C4::Log;
38 use C4::Letters;
39 use C4::Form::MessagingPreferences;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47 use Koha::Patron::HouseboundRole;
48 use Koha::Patron::HouseboundRoles;
49 use Koha::Token;
50 use Email::Valid;
51 use Module::Load;
52 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
53 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
55 use Koha::SMS::Providers;
57 use vars qw($debug);
59 BEGIN {
60 $debug = $ENV{DEBUG} || 0;
63 my $input = new CGI;
64 ($debug) or $debug = $input->param('debug') || 0;
65 my %data;
67 my $dbh = C4::Context->dbh;
69 my ($template, $loggedinuser, $cookie)
70 = get_template_and_user({template_name => "members/memberentrygen.tt",
71 query => $input,
72 type => "intranet",
73 authnotrequired => 0,
74 flagsrequired => {borrowers => 1},
75 debug => ($debug) ? 1 : 0,
76 });
78 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
79 my @providers = Koha::SMS::Providers->search();
80 $template->param( sms_providers => \@providers );
83 my $guarantorid = $input->param('guarantorid');
84 my $borrowernumber = $input->param('borrowernumber');
85 my $actionType = $input->param('actionType') || '';
86 my $modify = $input->param('modify');
87 my $delete = $input->param('delete');
88 my $op = $input->param('op');
89 my $destination = $input->param('destination');
90 my $cardnumber = $input->param('cardnumber');
91 my $check_member = $input->param('check_member');
92 my $nodouble = $input->param('nodouble');
93 my $duplicate = $input->param('duplicate');
94 my $quickadd = $input->param('quickadd');
95 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
96 # modifying an existing patron, it ipso facto
97 # isn't a duplicate. Marking FIXME because this
98 # script needs to be refactored.
99 my $nok = $input->param('nok');
100 my $guarantorinfo = $input->param('guarantorinfo');
101 my $step = $input->param('step') || 0;
102 my @errors;
103 my $borrower_data;
104 my $NoUpdateLogin;
105 my $userenv = C4::Context->userenv;
108 ## Deal with debarments
109 $template->param(
110 debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
111 my @debarments_to_remove = $input->multi_param('remove_debarment');
112 foreach my $d ( @debarments_to_remove ) {
113 DelDebarment( $d );
115 if ( $input->param('add_debarment') ) {
117 my $expiration = $input->param('debarred_expiration');
118 $expiration =
119 $expiration
120 ? output_pref(
121 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
122 : undef;
124 AddDebarment(
126 borrowernumber => $borrowernumber,
127 type => 'MANUAL',
128 comment => scalar $input->param('debarred_comment'),
129 expiration => $expiration,
134 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
136 my $minpw = C4::Context->preference('minPasswordLength');
137 $template->param("minPasswordLength" => $minpw);
139 # function to designate mandatory fields (visually with css)
140 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
141 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
142 foreach (@field_check) {
143 $template->param( "mandatory$_" => 1);
145 # function to designate unwanted fields
146 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
147 @field_check=split(/\|/,$check_BorrowerUnwantedField);
148 foreach (@field_check) {
149 next unless m/\w/o;
150 $template->param( "no$_" => 1);
152 $template->param( "add" => 1 ) if ( $op eq 'add' );
153 $template->param( "quickadd" => 1 ) if ( $quickadd );
154 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
155 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
156 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
157 my $patron = Koha::Patrons->find( $borrowernumber );
158 unless ( $patron ) {
159 print $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber");
160 exit;
163 $borrower_data = $patron->unblessed;
164 $borrower_data->{category_type} = $patron->category->category_type;
166 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
167 my $category_type = $input->param('category_type') || '';
168 unless ($category_type or !($categorycode)){
169 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
170 $category_type = $borrowercategory->category_type;
171 my $category_name = $borrowercategory->description;
172 $template->param("categoryname"=>$category_name);
174 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
176 # if a add or modify is requested => check validity of data.
177 %data = %$borrower_data if ($borrower_data);
179 # initialize %newdata
180 my %newdata; # comes from $input->param()
181 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
182 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
183 foreach my $key (@names) {
184 if (defined $input->param($key)) {
185 $newdata{$key} = $input->param($key);
186 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
190 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
191 next unless exists $newdata{$_};
192 my $userdate = $newdata{$_} or next;
194 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
195 if ( $formatteddate ) {
196 $newdata{$_} = $formatteddate;
197 } else {
198 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
199 $template->param( "ERROR_$_" => 1 );
200 push(@errors,"ERROR_$_");
203 # check permission to modify login info.
204 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
205 $NoUpdateLogin = 1;
209 # remove keys from %newdata that ModMember() doesn't like
211 my @keys_to_delete = (
212 qr/^BorrowerMandatoryField$/,
213 qr/^category_type$/,
214 qr/^check_member$/,
215 qr/^destination$/,
216 qr/^nodouble$/,
217 qr/^op$/,
218 qr/^save$/,
219 qr/^updtype$/,
220 qr/^SMSnumber$/,
221 qr/^setting_extended_patron_attributes$/,
222 qr/^setting_messaging_prefs$/,
223 qr/^digest$/,
224 qr/^modify$/,
225 qr/^step$/,
226 qr/^\d+$/,
227 qr/^\d+-DAYS/,
228 qr/^patron_attr_/,
230 for my $regexp (@keys_to_delete) {
231 for (keys %newdata) {
232 delete($newdata{$_}) if /$regexp/;
237 # Test uniqueness of surname, firstname and dateofbirth
238 if ( ( $op eq 'insert' ) and !$nodouble ) {
239 my $conditions;
240 $conditions->{surname} = $newdata{surname} if $newdata{surname};
241 if ( $category_type ne 'I' ) {
242 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
243 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
245 $nodouble = 1;
246 my $patrons = Koha::Patrons->search($conditions);
247 if ( $patrons->count > 0) {
248 $nodouble = 0;
249 $check_member = $patrons->next->borrowernumber;
253 #recover all data from guarantor address phone ,fax...
254 if ( $guarantorid ) {
255 if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
256 my $guarantordata = $guarantor->unblessed;
257 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
258 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
259 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
260 $newdata{'contactname'} = $guarantordata->{'surname'};
261 $newdata{'contacttitle'} = $guarantordata->{'title'};
262 if ( $op eq 'add' ) {
263 foreach (qw(streetnumber address streettype address2
264 zipcode country city state phone phonepro mobile fax email emailpro branchcode
265 B_streetnumber B_streettype B_address B_address2
266 B_city B_state B_zipcode B_country B_email B_phone)) {
267 $newdata{$_} = $guarantordata->{$_};
273 ###############test to take the right zipcode, country and city name ##############
274 # set only if parameter was passed from the form
275 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
276 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
277 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
279 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
281 # builds default userid
282 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
283 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
284 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
285 # Full page edit, firstname and surname input zones are present
286 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
288 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
289 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
290 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
291 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
293 else {
294 $newdata{'userid'} = $data{'userid'};
298 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
299 my $extended_patron_attributes = ();
300 if ($op eq 'save' || $op eq 'insert'){
302 die "Wrong CSRF token"
303 unless Koha::Token->new->check_csrf({
304 session_id => scalar $input->cookie('CGISESSID'),
305 token => scalar $input->param('csrf_token'),
308 # If the cardnumber is blank, treat it as null.
309 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
311 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
312 push @errors, $error_code == 1
313 ? 'ERROR_cardnumber_already_exists'
314 : $error_code == 2
315 ? 'ERROR_cardnumber_length'
316 : ()
319 my $dateofbirth;
320 if ($op eq 'save' && $step == 3) {
321 my $patron = Koha::Patrons->find( $borrowernumber );
322 $dateofbirth = $patron->dateofbirth;
324 else {
325 $dateofbirth = $newdata{dateofbirth};
328 if ( $dateofbirth ) {
329 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
330 my $age = $patron->get_age;
331 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
332 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
333 if (($high && ($age > $high)) or ($age < $low)) {
334 push @errors, 'ERROR_age_limitations';
335 $template->param( age_low => $low);
336 $template->param( age_high => $high);
340 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
341 $newdata{'surname'} = uc($newdata{'surname'});
344 if (C4::Context->preference("IndependentBranches")) {
345 unless ( C4::Context->IsSuperLibrarian() ){
346 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
347 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
348 push @errors, "ERROR_branch";
352 # Check if the 'userid' is unique. 'userid' might not always be present in
353 # the edited values list when editing certain sub-forms. Get it straight
354 # from the DB if absent.
355 my $userid = $newdata{ userid } // $borrower_data->{ userid };
356 unless (Check_Userid($userid,$borrowernumber)) {
357 push @errors, "ERROR_login_exist";
360 my $password = $input->param('password');
361 my $password2 = $input->param('password2');
362 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
363 push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
365 # Validate emails
366 my $emailprimary = $input->param('email');
367 my $emailsecondary = $input->param('emailpro');
368 my $emailalt = $input->param('B_email');
370 if ($emailprimary) {
371 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
373 if ($emailsecondary) {
374 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
376 if ($emailalt) {
377 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
380 if (C4::Context->preference('ExtendedPatronAttributes')) {
381 $extended_patron_attributes = parse_extended_patron_attributes($input);
382 foreach my $attr (@$extended_patron_attributes) {
383 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
384 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
385 push @errors, "ERROR_extended_unique_id_failed";
386 $template->param(
387 ERROR_extended_unique_id_failed_code => $attr->{code},
388 ERROR_extended_unique_id_failed_value => $attr->{value},
389 ERROR_extended_unique_id_failed_description => $attr_info->description()
396 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
397 unless ($newdata{'dateexpiry'}){
398 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
399 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
403 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
404 my $sms = $input->param('SMSnumber');
405 if ( defined $sms ) {
406 $newdata{smsalertnumber} = $sms;
409 ### Error checks should happen before this line.
410 $nok = $nok || scalar(@errors);
411 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
412 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
413 if ($op eq 'insert'){
414 # we know it's not a duplicate borrowernumber or there would already be an error
415 $borrowernumber = &AddMember(%newdata);
416 $newdata{'borrowernumber'} = $borrowernumber;
418 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
419 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
420 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
421 my $emailaddr;
422 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
423 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
424 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
426 elsif ($newdata{email} =~ /\w\@\w/) {
427 $emailaddr = $newdata{email}
429 elsif ($newdata{emailpro} =~ /\w\@\w/) {
430 $emailaddr = $newdata{emailpro}
432 elsif ($newdata{B_email} =~ /\w\@\w/) {
433 $emailaddr = $newdata{B_email}
435 # if we manage to find a valid email address, send notice
436 if ($emailaddr) {
437 $newdata{emailaddr} = $emailaddr;
438 my $err;
439 eval {
440 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
442 if ( $@ ) {
443 $template->param(error_alert => $@);
444 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
445 $template->{VARS}->{'error_alert'} = "no_email";
446 } else {
447 $template->{VARS}->{'info_alert'} = 1;
452 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
453 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
455 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
456 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
458 # Try to do the live sync with the Norwegian national patron database, if it is enabled
459 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
460 NLSync({ 'borrowernumber' => $borrowernumber });
463 # Create HouseboundRole if necessary.
464 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
465 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
466 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
467 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
468 # Only create a HouseboundRole if patron has a role.
469 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
470 Koha::Patron::HouseboundRole->new({
471 borrowernumber_id => $borrowernumber,
472 housebound_chooser => $hsbnd_chooser,
473 housebound_deliverer => $hsbnd_deliverer,
474 })->store;
477 } elsif ($op eq 'save') {
479 # Update or create our HouseboundRole if necessary.
480 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
481 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
482 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
483 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
484 if ( $housebound_role ) {
485 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
486 # Update our HouseboundRole.
487 $housebound_role
488 ->housebound_chooser($hsbnd_chooser)
489 ->housebound_deliverer($hsbnd_deliverer)
490 ->store;
491 } else {
492 $housebound_role->delete; # No longer needed.
494 } else {
495 # Only create a HouseboundRole if patron has a role.
496 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
497 $housebound_role = Koha::Patron::HouseboundRole->new({
498 borrowernumber_id => $borrowernumber,
499 housebound_chooser => $hsbnd_chooser,
500 housebound_deliverer => $hsbnd_deliverer,
501 })->store;
505 if ($NoUpdateLogin) {
506 delete $newdata{'password'};
507 delete $newdata{'userid'};
509 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
510 # updating any columns in the borrowers table,
511 # which can happen if we're only editing the
512 # patron attributes or messaging preferences sections
513 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
514 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
516 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
517 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
520 print scalar ($destination eq "circ") ?
521 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
522 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
523 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
526 if ($delete){
527 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
528 exit; # same as above
531 if ($nok or !$nodouble){
532 $op="add" if ($op eq "insert");
533 $op="modify" if ($op eq "save");
534 %data=%newdata;
535 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
536 unless ($step){
537 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
540 if (C4::Context->preference("IndependentBranches")) {
541 my $userenv = C4::Context->userenv;
542 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
543 unless ($userenv->{branch} eq $data{'branchcode'}){
544 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
545 exit;
549 if ($op eq 'add'){
550 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
552 if ($op eq "modify") {
553 $template->param( updtype => 'M',modify => 1 );
554 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
555 if ( $step == 4 ) {
556 $template->param( categorycode => $borrower_data->{'categorycode'} );
558 # Add sync data to the user data
559 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
560 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
561 if ( $sync ) {
562 $template->param(
563 sync => $sync->sync,
568 if ( $op eq "duplicate" ) {
569 $template->param( updtype => 'I' );
570 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
571 $data{'cardnumber'} = "";
574 if(!defined($data{'sex'})){
575 $template->param( none => 1);
576 } elsif($data{'sex'} eq 'F'){
577 $template->param( female => 1);
578 } elsif ($data{'sex'} eq 'M'){
579 $template->param( male => 1);
580 } else {
581 $template->param( none => 1);
584 ##Now all the data to modify a member.
586 my @typeloop;
587 my $no_categories = 1;
588 my $no_add;
589 foreach my $category_type (qw(C A S P I X)) {
590 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
591 $no_categories = 0 if $patron_categories->count > 0;
593 my @categoryloop;
594 while ( my $patron_category = $patron_categories->next ) {
595 push @categoryloop,
596 { 'categorycode' => $patron_category->categorycode,
597 'categoryname' => $patron_category->description,
598 'categorycodeselected' =>
599 ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
602 my %typehash;
603 $typehash{'typename'} = $category_type;
604 my $typedescription = "typename_" . $typehash{'typename'};
605 $typehash{'categoryloop'} = \@categoryloop;
606 push @typeloop,
607 { 'typename' => $category_type,
608 $typedescription => 1,
609 'categoryloop' => \@categoryloop
613 $template->param('typeloop' => \@typeloop,
614 no_categories => $no_categories);
615 if($no_categories){ $no_add = 1; }
618 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
619 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
620 $template->param(
621 roadtypes => $roadtypes,
622 cities => $cities,
625 my $default_borrowertitle = '';
626 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
628 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
629 my @relshipdata;
630 while (@relationships) {
631 my $relship = shift @relationships || '';
632 my %row = ('relationship' => $relship);
633 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
634 $row{'selected'}=' selected';
635 } else {
636 $row{'selected'}='';
638 push(@relshipdata, \%row);
641 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
642 'lost' => ['lost']);
645 my @flagdata;
646 foreach (keys(%flags)) {
647 my $key = $_;
648 my %row = ('key' => $key,
649 'name' => $flags{$key}[0]);
650 if ($data{$key}) {
651 $row{'yes'}=' checked';
652 $row{'no'}='';
654 else {
655 $row{'yes'}='';
656 $row{'no'}=' checked';
658 push @flagdata,\%row;
661 # get Branch Loop
662 # in modify mod: userbranch value comes from borrowers table
663 # in add mod: userbranch value comes from branches table (ip correspondence)
665 my $userbranch = '';
666 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
667 $userbranch = C4::Context->userenv->{'branch'};
670 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
671 $userbranch = $data{'branchcode'};
673 $template->param( userbranch => $userbranch );
675 if ( Koha::Libraries->search->count < 1 ){
676 $no_add = 1;
677 $template->param(no_branches => 1);
679 if($no_categories){
680 $no_add = 1;
681 $template->param(no_categories => 1);
683 $template->param(no_add => $no_add);
684 # --------------------------------------------------------------------------------------------------------
686 $template->param( sort1 => $data{'sort1'});
687 $template->param( sort2 => $data{'sort2'});
689 if ($nok) {
690 foreach my $error (@errors) {
691 $template->param($error) || $template->param( $error => 1);
693 $template->param(nok => 1);
696 #Formatting data for display
698 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
699 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
701 if ( $op eq 'duplicate' ) {
702 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
703 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
704 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
706 if (C4::Context->preference('uppercasesurnames')) {
707 $data{'surname'} &&= uc( $data{'surname'} );
708 $data{'contactname'} &&= uc( $data{'contactname'} );
711 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
712 if ( $data{$_} ) {
713 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
715 $template->param( $_ => $data{$_});
718 if (C4::Context->preference('ExtendedPatronAttributes')) {
719 $template->param(ExtendedPatronAttributes => 1);
720 patron_attributes_form($template, $borrowernumber);
723 if (C4::Context->preference('EnhancedMessagingPreferences')) {
724 if ($op eq 'add') {
725 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
726 } else {
727 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
729 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
730 $template->param(SMSnumber => $data{'smsalertnumber'} );
731 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
734 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
735 $debug and warn "memberentry step: $step";
736 $template->param(%data);
737 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
738 $template->param( step => $step ) if $step; # associate with step to know where u are
740 $template->param(
741 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
742 category_type => $category_type,#to know the category type of the borrower
743 "$category_type" => 1,# associate with step to know where u are
744 destination => $destination,#to know wher u come from and wher u must go in redirect
745 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
746 "op$op" => 1);
748 $template->param(
749 nodouble => $nodouble,
750 borrowernumber => $borrowernumber, #register number
751 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
752 relshiploop => \@relshipdata,
753 btitle=> $default_borrowertitle,
754 guarantorinfo => $guarantorinfo,
755 flagloop => \@flagdata,
756 category_type =>$category_type,
757 modify => $modify,
758 nok => $nok,#flag to know if an error
759 NoUpdateLogin => $NoUpdateLogin,
762 # Generate CSRF token
763 $template->param( csrf_token =>
764 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
767 # HouseboundModule data
768 $template->param(
769 housebound_role => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
772 if(defined($data{'flags'})){
773 $template->param(flags=>$data{'flags'});
775 if(defined($data{'contacttitle'})){
776 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
780 my ( $min, $max ) = C4::Members::get_cardnumber_length();
781 if ( defined $min ) {
782 $template->param(
783 minlength_cardnumber => $min,
784 maxlength_cardnumber => $max
788 if ( C4::Context->preference('TranslateNotices') ) {
789 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
790 $template->param( languages => $translated_languages );
793 output_html_with_http_headers $input, $cookie, $template->output;
795 sub parse_extended_patron_attributes {
796 my ($input) = @_;
797 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
799 my @attr = ();
800 my %dups = ();
801 foreach my $key (@patron_attr) {
802 my $value = $input->param($key);
803 next unless defined($value) and $value ne '';
804 my $code = $input->param("${key}_code");
805 next if exists $dups{$code}->{$value};
806 $dups{$code}->{$value} = 1;
807 push @attr, { code => $code, value => $value };
809 return \@attr;
812 sub patron_attributes_form {
813 my $template = shift;
814 my $borrowernumber = shift;
816 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
817 if (scalar(@types) == 0) {
818 $template->param(no_patron_attribute_types => 1);
819 return;
821 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
822 my @classes = uniq( map {$_->{class}} @$attributes );
823 @classes = sort @classes;
825 # map patron's attributes into a more convenient structure
826 my %attr_hash = ();
827 foreach my $attr (@$attributes) {
828 push @{ $attr_hash{$attr->{code}} }, $attr;
831 my @attribute_loop = ();
832 my $i = 0;
833 my %items_by_class;
834 foreach my $type_code (map { $_->{code} } @types) {
835 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
836 my $entry = {
837 class => $attr_type->class(),
838 code => $attr_type->code(),
839 description => $attr_type->description(),
840 repeatable => $attr_type->repeatable(),
841 category => $attr_type->authorised_value_category(),
842 category_code => $attr_type->category_code(),
844 if (exists $attr_hash{$attr_type->code()}) {
845 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
846 my $newentry = { %$entry };
847 $newentry->{value} = $attr->{value};
848 $newentry->{use_dropdown} = 0;
849 if ($attr_type->authorised_value_category()) {
850 $newentry->{use_dropdown} = 1;
851 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
853 $i++;
854 $newentry->{form_id} = "patron_attr_$i";
855 push @{$items_by_class{$attr_type->class()}}, $newentry;
857 } else {
858 $i++;
859 my $newentry = { %$entry };
860 if ($attr_type->authorised_value_category()) {
861 $newentry->{use_dropdown} = 1;
862 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
864 $newentry->{form_id} = "patron_attr_$i";
865 push @{$items_by_class{$attr_type->class()}}, $newentry;
868 while ( my ($class, @items) = each %items_by_class ) {
869 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
870 my $lib = $av->count ? $av->next->lib : $class;
871 push @attribute_loop, {
872 class => $class,
873 items => @items,
874 lib => $lib,
878 $template->param(patron_attributes => \@attribute_loop);
882 # Local Variables:
883 # tab-width: 8
884 # End: