Bug 18807: t/db_dependent/www/batch.t fails
[koha.git] / members / memberentry.pl
blob2ffea5de4ce0b1f8c3d912cafbfab2f085ac4afe
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::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
48 use Koha::Token;
49 use Email::Valid;
50 use Module::Load;
51 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
52 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
54 use Koha::SMS::Providers;
56 use vars qw($debug);
58 BEGIN {
59 $debug = $ENV{DEBUG} || 0;
62 my $input = new CGI;
63 ($debug) or $debug = $input->param('debug') || 0;
64 my %data;
66 my $dbh = C4::Context->dbh;
68 my ($template, $loggedinuser, $cookie)
69 = get_template_and_user({template_name => "members/memberentrygen.tt",
70 query => $input,
71 type => "intranet",
72 authnotrequired => 0,
73 flagsrequired => {borrowers => 1},
74 debug => ($debug) ? 1 : 0,
75 });
77 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
78 my @providers = Koha::SMS::Providers->search();
79 $template->param( sms_providers => \@providers );
82 my $guarantorid = $input->param('guarantorid');
83 my $borrowernumber = $input->param('borrowernumber');
84 my $actionType = $input->param('actionType') || '';
85 my $modify = $input->param('modify');
86 my $delete = $input->param('delete');
87 my $op = $input->param('op');
88 my $destination = $input->param('destination');
89 my $cardnumber = $input->param('cardnumber');
90 my $check_member = $input->param('check_member');
91 my $nodouble = $input->param('nodouble');
92 my $duplicate = $input->param('duplicate');
93 my $quickadd = $input->param('quickadd');
94 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
95 # modifying an existing patron, it ipso facto
96 # isn't a duplicate. Marking FIXME because this
97 # script needs to be refactored.
98 my $nok = $input->param('nok');
99 my $guarantorinfo = $input->param('guarantorinfo');
100 my $step = $input->param('step') || 0;
101 my @errors;
102 my $borrower_data;
103 my $NoUpdateLogin;
104 my $userenv = C4::Context->userenv;
107 ## Deal with debarments
108 $template->param(
109 debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
110 my @debarments_to_remove = $input->multi_param('remove_debarment');
111 foreach my $d ( @debarments_to_remove ) {
112 DelDebarment( $d );
114 if ( $input->param('add_debarment') ) {
116 my $expiration = $input->param('debarred_expiration');
117 $expiration =
118 $expiration
119 ? output_pref(
120 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
121 : undef;
123 AddDebarment(
125 borrowernumber => $borrowernumber,
126 type => 'MANUAL',
127 comment => scalar $input->param('debarred_comment'),
128 expiration => $expiration,
133 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
135 my $minpw = C4::Context->preference('minPasswordLength');
136 $template->param("minPasswordLength" => $minpw);
138 # function to designate mandatory fields (visually with css)
139 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
140 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
141 foreach (@field_check) {
142 $template->param( "mandatory$_" => 1);
144 # function to designate unwanted fields
145 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
146 @field_check=split(/\|/,$check_BorrowerUnwantedField);
147 foreach (@field_check) {
148 next unless m/\w/o;
149 $template->param( "no$_" => 1);
151 $template->param( "add" => 1 ) if ( $op eq 'add' );
152 $template->param( "quickadd" => 1 ) if ( $quickadd );
153 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
154 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
155 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
156 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
157 my $category_type = $input->param('category_type') || '';
158 unless ($category_type or !($categorycode)){
159 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
160 $category_type = $borrowercategory->category_type;
161 my $category_name = $borrowercategory->description;
162 $template->param("categoryname"=>$category_name);
164 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
166 # if a add or modify is requested => check validity of data.
167 %data = %$borrower_data if ($borrower_data);
169 # initialize %newdata
170 my %newdata; # comes from $input->param()
171 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
172 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
173 foreach my $key (@names) {
174 if (defined $input->param($key)) {
175 $newdata{$key} = $input->param($key);
176 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
180 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
181 next unless exists $newdata{$_};
182 my $userdate = $newdata{$_} or next;
184 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
185 if ( $formatteddate ) {
186 $newdata{$_} = $formatteddate;
187 } else {
188 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
189 $template->param( "ERROR_$_" => 1 );
190 push(@errors,"ERROR_$_");
193 # check permission to modify login info.
194 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
195 $NoUpdateLogin = 1;
199 # remove keys from %newdata that ModMember() doesn't like
201 my @keys_to_delete = (
202 qr/^BorrowerMandatoryField$/,
203 qr/^category_type$/,
204 qr/^check_member$/,
205 qr/^destination$/,
206 qr/^nodouble$/,
207 qr/^op$/,
208 qr/^save$/,
209 qr/^updtype$/,
210 qr/^SMSnumber$/,
211 qr/^setting_extended_patron_attributes$/,
212 qr/^setting_messaging_prefs$/,
213 qr/^digest$/,
214 qr/^modify$/,
215 qr/^step$/,
216 qr/^\d+$/,
217 qr/^\d+-DAYS/,
218 qr/^patron_attr_/,
220 for my $regexp (@keys_to_delete) {
221 for (keys %newdata) {
222 delete($newdata{$_}) if /$regexp/;
227 # Test uniqueness of surname, firstname and dateofbirth
228 if ( ( $op eq 'insert' ) and !$nodouble ) {
229 my $conditions;
230 $conditions->{surname} = $newdata{surname} if $newdata{surname};
231 if ( $category_type ne 'I' ) {
232 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
233 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
235 $nodouble = 1;
236 my $patrons = Koha::Patrons->search($conditions);
237 if ( $patrons->count > 0) {
238 $nodouble = 0;
239 $check_member = $patrons->next->borrowernumber;
243 #recover all data from guarantor address phone ,fax...
244 if ( $guarantorid ) {
245 if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
246 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
247 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
248 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
249 $newdata{'contactname'} = $guarantordata->{'surname'};
250 $newdata{'contacttitle'} = $guarantordata->{'title'};
251 if ( $op eq 'add' ) {
252 foreach (qw(streetnumber address streettype address2
253 zipcode country city state phone phonepro mobile fax email emailpro branchcode
254 B_streetnumber B_streettype B_address B_address2
255 B_city B_state B_zipcode B_country B_email B_phone)) {
256 $newdata{$_} = $guarantordata->{$_};
262 ###############test to take the right zipcode, country and city name ##############
263 # set only if parameter was passed from the form
264 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
265 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
266 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
268 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
270 # builds default userid
271 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
272 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
273 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
274 # Full page edit, firstname and surname input zones are present
275 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
277 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
278 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
279 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
280 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
282 else {
283 $newdata{'userid'} = $data{'userid'};
287 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
288 my $extended_patron_attributes = ();
289 if ($op eq 'save' || $op eq 'insert'){
291 die "Wrong CSRF token"
292 unless Koha::Token->new->check_csrf({
293 session_id => scalar $input->cookie('CGISESSID'),
294 token => scalar $input->param('csrf_token'),
297 # If the cardnumber is blank, treat it as null.
298 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
300 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
301 push @errors, $error_code == 1
302 ? 'ERROR_cardnumber_already_exists'
303 : $error_code == 2
304 ? 'ERROR_cardnumber_length'
305 : ()
308 my $dateofbirth;
309 if ($op eq 'save' && $step == 3) {
310 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
311 $dateofbirth = $borrower->{dateofbirth};
313 else {
314 $dateofbirth = $newdata{dateofbirth};
317 if ( $dateofbirth ) {
318 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
319 my $age = $patron->get_age;
320 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
321 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
322 if (($high && ($age > $high)) or ($age < $low)) {
323 push @errors, 'ERROR_age_limitations';
324 $template->param( age_low => $low);
325 $template->param( age_high => $high);
329 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
330 $newdata{'surname'} = uc($newdata{'surname'});
333 if (C4::Context->preference("IndependentBranches")) {
334 unless ( C4::Context->IsSuperLibrarian() ){
335 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
336 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
337 push @errors, "ERROR_branch";
341 # Check if the 'userid' is unique. 'userid' might not always be present in
342 # the edited values list when editing certain sub-forms. Get it straight
343 # from the DB if absent.
344 my $userid = $newdata{ userid } // $borrower_data->{ userid };
345 unless (Check_Userid($userid,$borrowernumber)) {
346 push @errors, "ERROR_login_exist";
349 my $password = $input->param('password');
350 my $password2 = $input->param('password2');
351 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
352 push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
354 # Validate emails
355 my $emailprimary = $input->param('email');
356 my $emailsecondary = $input->param('emailpro');
357 my $emailalt = $input->param('B_email');
359 if ($emailprimary) {
360 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
362 if ($emailsecondary) {
363 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
365 if ($emailalt) {
366 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
369 if (C4::Context->preference('ExtendedPatronAttributes')) {
370 $extended_patron_attributes = parse_extended_patron_attributes($input);
371 foreach my $attr (@$extended_patron_attributes) {
372 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
373 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
374 push @errors, "ERROR_extended_unique_id_failed";
375 $template->param(
376 ERROR_extended_unique_id_failed_code => $attr->{code},
377 ERROR_extended_unique_id_failed_value => $attr->{value},
378 ERROR_extended_unique_id_failed_description => $attr_info->description()
385 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
386 unless ($newdata{'dateexpiry'}){
387 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
388 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
392 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
393 my $sms = $input->param('SMSnumber');
394 if ( defined $sms ) {
395 $newdata{smsalertnumber} = $sms;
398 ### Error checks should happen before this line.
399 $nok = $nok || scalar(@errors);
400 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
401 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
402 if ($op eq 'insert'){
403 # we know it's not a duplicate borrowernumber or there would already be an error
404 $borrowernumber = &AddMember(%newdata);
405 $newdata{'borrowernumber'} = $borrowernumber;
407 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
408 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
409 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
410 my $emailaddr;
411 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
412 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
413 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
415 elsif ($newdata{email} =~ /\w\@\w/) {
416 $emailaddr = $newdata{email}
418 elsif ($newdata{emailpro} =~ /\w\@\w/) {
419 $emailaddr = $newdata{emailpro}
421 elsif ($newdata{B_email} =~ /\w\@\w/) {
422 $emailaddr = $newdata{B_email}
424 # if we manage to find a valid email address, send notice
425 if ($emailaddr) {
426 $newdata{emailaddr} = $emailaddr;
427 my $err;
428 eval {
429 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
431 if ( $@ ) {
432 $template->param(error_alert => $@);
433 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
434 $template->{VARS}->{'error_alert'} = "no_email";
435 } else {
436 $template->{VARS}->{'info_alert'} = 1;
441 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
442 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
444 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
445 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
447 # Try to do the live sync with the Norwegian national patron database, if it is enabled
448 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
449 NLSync({ 'borrowernumber' => $borrowernumber });
452 # Create HouseboundRole if necessary.
453 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
454 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
455 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
456 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
457 # Only create a HouseboundRole if patron has a role.
458 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
459 Koha::Patron::HouseboundRole->new({
460 borrowernumber_id => $borrowernumber,
461 housebound_chooser => $hsbnd_chooser,
462 housebound_deliverer => $hsbnd_deliverer,
463 })->store;
466 } elsif ($op eq 'save') {
468 # Update or create our HouseboundRole if necessary.
469 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
470 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
471 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
472 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
473 if ( $housebound_role ) {
474 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
475 # Update our HouseboundRole.
476 $housebound_role
477 ->housebound_chooser($hsbnd_chooser)
478 ->housebound_deliverer($hsbnd_deliverer)
479 ->store;
480 } else {
481 $housebound_role->delete; # No longer needed.
483 } else {
484 # Only create a HouseboundRole if patron has a role.
485 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
486 $housebound_role = Koha::Patron::HouseboundRole->new({
487 borrowernumber_id => $borrowernumber,
488 housebound_chooser => $hsbnd_chooser,
489 housebound_deliverer => $hsbnd_deliverer,
490 })->store;
494 if ($NoUpdateLogin) {
495 delete $newdata{'password'};
496 delete $newdata{'userid'};
498 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
499 # updating any columns in the borrowers table,
500 # which can happen if we're only editing the
501 # patron attributes or messaging preferences sections
502 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
503 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
505 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
506 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
509 print scalar ($destination eq "circ") ?
510 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
511 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
512 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
515 if ($delete){
516 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
517 exit; # same as above
520 if ($nok or !$nodouble){
521 $op="add" if ($op eq "insert");
522 $op="modify" if ($op eq "save");
523 %data=%newdata;
524 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
525 unless ($step){
526 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
529 if (C4::Context->preference("IndependentBranches")) {
530 my $userenv = C4::Context->userenv;
531 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
532 unless ($userenv->{branch} eq $data{'branchcode'}){
533 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
534 exit;
538 if ($op eq 'add'){
539 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
541 if ($op eq "modify") {
542 $template->param( updtype => 'M',modify => 1 );
543 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
544 if ( $step == 4 ) {
545 $template->param( categorycode => $borrower_data->{'categorycode'} );
547 # Add sync data to the user data
548 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
549 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
550 if ( $sync ) {
551 $template->param(
552 sync => $sync->sync,
557 if ( $op eq "duplicate" ) {
558 $template->param( updtype => 'I' );
559 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
560 $data{'cardnumber'} = "";
563 if(!defined($data{'sex'})){
564 $template->param( none => 1);
565 } elsif($data{'sex'} eq 'F'){
566 $template->param( female => 1);
567 } elsif ($data{'sex'} eq 'M'){
568 $template->param( male => 1);
569 } else {
570 $template->param( none => 1);
573 ##Now all the data to modify a member.
575 my @typeloop;
576 my $no_categories = 1;
577 my $no_add;
578 foreach my $category_type (qw(C A S P I X)) {
579 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
580 $no_categories = 0 if $patron_categories->count > 0;
582 my @categoryloop;
583 while ( my $patron_category = $patron_categories->next ) {
584 push @categoryloop,
585 { 'categorycode' => $patron_category->categorycode,
586 'categoryname' => $patron_category->description,
587 'categorycodeselected' =>
588 ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
591 my %typehash;
592 $typehash{'typename'} = $category_type;
593 my $typedescription = "typename_" . $typehash{'typename'};
594 $typehash{'categoryloop'} = \@categoryloop;
595 push @typeloop,
596 { 'typename' => $category_type,
597 $typedescription => 1,
598 'categoryloop' => \@categoryloop
602 $template->param('typeloop' => \@typeloop,
603 no_categories => $no_categories);
604 if($no_categories){ $no_add = 1; }
607 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
608 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
609 $template->param(
610 roadtypes => $roadtypes,
611 cities => $cities,
614 my $default_borrowertitle = '';
615 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
617 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
618 my @relshipdata;
619 while (@relationships) {
620 my $relship = shift @relationships || '';
621 my %row = ('relationship' => $relship);
622 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
623 $row{'selected'}=' selected';
624 } else {
625 $row{'selected'}='';
627 push(@relshipdata, \%row);
630 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
631 'lost' => ['lost']);
634 my @flagdata;
635 foreach (keys(%flags)) {
636 my $key = $_;
637 my %row = ('key' => $key,
638 'name' => $flags{$key}[0]);
639 if ($data{$key}) {
640 $row{'yes'}=' checked';
641 $row{'no'}='';
643 else {
644 $row{'yes'}='';
645 $row{'no'}=' checked';
647 push @flagdata,\%row;
650 # get Branch Loop
651 # in modify mod: userbranch value comes from borrowers table
652 # in add mod: userbranch value comes from branches table (ip correspondence)
654 my $userbranch = '';
655 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
656 $userbranch = C4::Context->userenv->{'branch'};
659 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
660 $userbranch = $data{'branchcode'};
662 $template->param( userbranch => $userbranch );
664 if ( Koha::Libraries->search->count < 1 ){
665 $no_add = 1;
666 $template->param(no_branches => 1);
668 if($no_categories){
669 $no_add = 1;
670 $template->param(no_categories => 1);
672 $template->param(no_add => $no_add);
673 # --------------------------------------------------------------------------------------------------------
675 $template->param( sort1 => $data{'sort1'});
676 $template->param( sort2 => $data{'sort2'});
678 if ($nok) {
679 foreach my $error (@errors) {
680 $template->param($error) || $template->param( $error => 1);
682 $template->param(nok => 1);
685 #Formatting data for display
687 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
688 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
690 if ( $op eq 'duplicate' ) {
691 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
692 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
693 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
695 if (C4::Context->preference('uppercasesurnames')) {
696 $data{'surname'} &&= uc( $data{'surname'} );
697 $data{'contactname'} &&= uc( $data{'contactname'} );
700 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
701 if ( $data{$_} ) {
702 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
704 $template->param( $_ => $data{$_});
707 if (C4::Context->preference('ExtendedPatronAttributes')) {
708 $template->param(ExtendedPatronAttributes => 1);
709 patron_attributes_form($template, $borrowernumber);
712 if (C4::Context->preference('EnhancedMessagingPreferences')) {
713 if ($op eq 'add') {
714 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
715 } else {
716 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
718 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
719 $template->param(SMSnumber => $data{'smsalertnumber'} );
720 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
723 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
724 $debug and warn "memberentry step: $step";
725 $template->param(%data);
726 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
727 $template->param( step => $step ) if $step; # associate with step to know where u are
729 $template->param(
730 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
731 category_type => $category_type,#to know the category type of the borrower
732 "$category_type" => 1,# associate with step to know where u are
733 destination => $destination,#to know wher u come from and wher u must go in redirect
734 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
735 "op$op" => 1);
737 $template->param(
738 nodouble => $nodouble,
739 borrowernumber => $borrowernumber, #register number
740 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
741 relshiploop => \@relshipdata,
742 btitle=> $default_borrowertitle,
743 guarantorinfo => $guarantorinfo,
744 flagloop => \@flagdata,
745 category_type =>$category_type,
746 modify => $modify,
747 nok => $nok,#flag to know if an error
748 NoUpdateLogin => $NoUpdateLogin,
751 # Generate CSRF token
752 $template->param( csrf_token =>
753 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
756 # HouseboundModule data
757 $template->param(
758 housebound_role => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
761 if(defined($data{'flags'})){
762 $template->param(flags=>$data{'flags'});
764 if(defined($data{'contacttitle'})){
765 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
769 my ( $min, $max ) = C4::Members::get_cardnumber_length();
770 if ( defined $min ) {
771 $template->param(
772 minlength_cardnumber => $min,
773 maxlength_cardnumber => $max
777 if ( C4::Context->preference('TranslateNotices') ) {
778 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
779 $template->param( languages => $translated_languages );
782 output_html_with_http_headers $input, $cookie, $template->output;
784 sub parse_extended_patron_attributes {
785 my ($input) = @_;
786 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
788 my @attr = ();
789 my %dups = ();
790 foreach my $key (@patron_attr) {
791 my $value = $input->param($key);
792 next unless defined($value) and $value ne '';
793 my $code = $input->param("${key}_code");
794 next if exists $dups{$code}->{$value};
795 $dups{$code}->{$value} = 1;
796 push @attr, { code => $code, value => $value };
798 return \@attr;
801 sub patron_attributes_form {
802 my $template = shift;
803 my $borrowernumber = shift;
805 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
806 if (scalar(@types) == 0) {
807 $template->param(no_patron_attribute_types => 1);
808 return;
810 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
811 my @classes = uniq( map {$_->{class}} @$attributes );
812 @classes = sort @classes;
814 # map patron's attributes into a more convenient structure
815 my %attr_hash = ();
816 foreach my $attr (@$attributes) {
817 push @{ $attr_hash{$attr->{code}} }, $attr;
820 my @attribute_loop = ();
821 my $i = 0;
822 my %items_by_class;
823 foreach my $type_code (map { $_->{code} } @types) {
824 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
825 my $entry = {
826 class => $attr_type->class(),
827 code => $attr_type->code(),
828 description => $attr_type->description(),
829 repeatable => $attr_type->repeatable(),
830 category => $attr_type->authorised_value_category(),
831 category_code => $attr_type->category_code(),
833 if (exists $attr_hash{$attr_type->code()}) {
834 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
835 my $newentry = { %$entry };
836 $newentry->{value} = $attr->{value};
837 $newentry->{use_dropdown} = 0;
838 if ($attr_type->authorised_value_category()) {
839 $newentry->{use_dropdown} = 1;
840 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
842 $i++;
843 $newentry->{form_id} = "patron_attr_$i";
844 push @{$items_by_class{$attr_type->class()}}, $newentry;
846 } else {
847 $i++;
848 my $newentry = { %$entry };
849 if ($attr_type->authorised_value_category()) {
850 $newentry->{use_dropdown} = 1;
851 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
853 $newentry->{form_id} = "patron_attr_$i";
854 push @{$items_by_class{$attr_type->class()}}, $newentry;
857 while ( my ($class, @items) = each %items_by_class ) {
858 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
859 my $lib = $av->count ? $av->next->lib : $class;
860 push @attribute_loop, {
861 class => $class,
862 items => @items,
863 lib => $lib,
867 $template->param(patron_attributes => \@attribute_loop);
871 # Local Variables:
872 # tab-width: 8
873 # End: