Bug 9021 - Add SMS via email as an alternative to SMS services via SMS::Send drivers
[koha.git] / members / memberentry.pl
blob48ea65ee8ac9074483e6e9c17e254b0975abc1fa
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 Digest::MD5 qw(md5_base64);
28 use List::MoreUtils qw/uniq/;
30 # internal modules
31 use C4::Auth;
32 use C4::Context;
33 use C4::Output;
34 use C4::Members;
35 use C4::Members::Attributes;
36 use C4::Members::AttributeTypes;
37 use C4::Koha;
38 use C4::Log;
39 use C4::Letters;
40 use C4::Branch; # GetBranches
41 use C4::Form::MessagingPreferences;
42 use Koha::Borrower::Debarments;
43 use Koha::DateUtils;
44 use Email::Valid;
45 use Module::Load;
46 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
47 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
49 use Koha::SMS::Provider;
51 use vars qw($debug);
53 BEGIN {
54 $debug = $ENV{DEBUG} || 0;
57 my $input = new CGI;
58 ($debug) or $debug = $input->param('debug') || 0;
59 my %data;
61 my $dbh = C4::Context->dbh;
63 my ($template, $loggedinuser, $cookie)
64 = get_template_and_user({template_name => "members/memberentrygen.tt",
65 query => $input,
66 type => "intranet",
67 authnotrequired => 0,
68 flagsrequired => {borrowers => 1},
69 debug => ($debug) ? 1 : 0,
70 });
72 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
73 my @providers = Koha::SMS::Provider->all();
74 $template->param( sms_providers => \@providers );
77 my $guarantorid = $input->param('guarantorid');
78 my $borrowernumber = $input->param('borrowernumber');
79 my $actionType = $input->param('actionType') || '';
80 my $modify = $input->param('modify');
81 my $delete = $input->param('delete');
82 my $op = $input->param('op');
83 my $destination = $input->param('destination');
84 my $cardnumber = $input->param('cardnumber');
85 my $check_member = $input->param('check_member');
86 my $nodouble = $input->param('nodouble');
87 my $duplicate = $input->param('duplicate');
88 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
89 # modifying an existing patron, it ipso facto
90 # isn't a duplicate. Marking FIXME because this
91 # script needs to be refactored.
92 my $select_city = $input->param('select_city');
93 my $nok = $input->param('nok');
94 my $guarantorinfo = $input->param('guarantorinfo');
95 my $step = $input->param('step') || 0;
96 my @errors;
97 my $default_city;
98 my $borrower_data;
99 my $NoUpdateLogin;
100 my $userenv = C4::Context->userenv;
103 ## Deal with debarments
104 $template->param(
105 debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
106 my @debarments_to_remove = $input->param('remove_debarment');
107 foreach my $d ( @debarments_to_remove ) {
108 DelDebarment( $d );
110 if ( $input->param('add_debarment') ) {
112 my $expiration = $input->param('debarred_expiration');
113 $expiration =
114 $expiration
115 ? output_pref(
116 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
117 : undef;
119 AddDebarment(
121 borrowernumber => $borrowernumber,
122 type => 'MANUAL',
123 comment => $input->param('debarred_comment'),
124 expiration => $expiration,
129 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
131 my $minpw = C4::Context->preference('minPasswordLength');
132 $template->param("minPasswordLength" => $minpw);
134 # function to designate mandatory fields (visually with css)
135 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
136 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
137 foreach (@field_check) {
138 $template->param( "mandatory$_" => 1);
140 # function to designate unwanted fields
141 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
142 @field_check=split(/\|/,$check_BorrowerUnwantedField);
143 foreach (@field_check) {
144 next unless m/\w/o;
145 $template->param( "no$_" => 1);
147 $template->param( "add" => 1 ) if ( $op eq 'add' );
148 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
149 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
150 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
151 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
152 my $category_type = $input->param('category_type') || '';
153 unless ($category_type or !($categorycode)){
154 my $borrowercategory = GetBorrowercategory($categorycode);
155 $category_type = $borrowercategory->{'category_type'};
156 my $category_name = $borrowercategory->{'description'};
157 $template->param("categoryname"=>$category_name);
159 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
161 # if a add or modify is requested => check validity of data.
162 %data = %$borrower_data if ($borrower_data);
164 # initialize %newdata
165 my %newdata; # comes from $input->param()
166 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
167 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
168 foreach my $key (@names) {
169 if (defined $input->param($key)) {
170 $newdata{$key} = $input->param($key);
171 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
175 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
176 next unless exists $newdata{$_};
177 my $userdate = $newdata{$_} or next;
179 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
180 if ( $formatteddate ) {
181 $newdata{$_} = $formatteddate;
182 } else {
183 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
184 $template->param( "ERROR_$_" => 1 );
185 push(@errors,"ERROR_$_");
188 # check permission to modify login info.
189 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
190 $NoUpdateLogin = 1;
194 # remove keys from %newdata that ModMember() doesn't like
196 my @keys_to_delete = (
197 qr/^BorrowerMandatoryField$/,
198 qr/^category_type$/,
199 qr/^check_member$/,
200 qr/^destination$/,
201 qr/^nodouble$/,
202 qr/^op$/,
203 qr/^save$/,
204 qr/^updtype$/,
205 qr/^SMSnumber$/,
206 qr/^setting_extended_patron_attributes$/,
207 qr/^setting_messaging_prefs$/,
208 qr/^digest$/,
209 qr/^modify$/,
210 qr/^step$/,
211 qr/^\d+$/,
212 qr/^\d+-DAYS/,
213 qr/^patron_attr_/,
215 for my $regexp (@keys_to_delete) {
216 for (keys %newdata) {
217 delete($newdata{$_}) if /$regexp/;
222 #############test for member being unique #############
223 if ( ( $op eq 'insert' ) and !$nodouble ) {
224 my $category_type_send;
225 if ( $category_type eq 'I' ) {
226 $category_type_send = $category_type;
228 my $check_category; # recover the category code of the doublon suspect borrowers
229 # ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
230 ( $check_member, $check_category ) = checkuniquemember(
231 $category_type_send,
232 ( $newdata{surname} ? $newdata{surname} : $data{surname} ),
233 ( $newdata{firstname} ? $newdata{firstname} : $data{firstname} ),
234 ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
236 if ( !$check_member ) {
237 $nodouble = 1;
241 #recover all data from guarantor address phone ,fax...
242 if ( $guarantorid ) {
243 if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
244 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
245 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
246 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
247 $newdata{'contactname'} = $guarantordata->{'surname'};
248 $newdata{'contacttitle'} = $guarantordata->{'title'};
249 if ( $op eq 'add' ) {
250 foreach (qw(streetnumber address streettype address2
251 zipcode country city state phone phonepro mobile fax email emailpro branchcode
252 B_streetnumber B_streettype B_address B_address2
253 B_city B_state B_zipcode B_country B_email B_phone)) {
254 $newdata{$_} = $guarantordata->{$_};
260 ###############test to take the right zipcode, country and city name ##############
261 # set only if parameter was passed from the form
262 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
263 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
264 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
266 # builds default userid
267 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
268 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
269 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
270 # Full page edit, firstname and surname input zones are present
271 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
273 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
274 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
275 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
276 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
278 else {
279 $newdata{'userid'} = $data{'userid'};
283 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
284 my $extended_patron_attributes = ();
285 if ($op eq 'save' || $op eq 'insert'){
286 # If the cardnumber is blank, treat it as null.
287 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
289 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
290 push @errors, $error_code == 1
291 ? 'ERROR_cardnumber_already_exists'
292 : $error_code == 2
293 ? 'ERROR_cardnumber_length'
294 : ()
297 if ( $newdata{dateofbirth} ) {
298 my $age = GetAge($newdata{dateofbirth});
299 my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});
300 my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
301 if (($high && ($age > $high)) or ($age < $low)) {
302 push @errors, 'ERROR_age_limitations';
303 $template->param( age_low => $low);
304 $template->param( age_high => $high);
308 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
309 $newdata{'surname'} = uc($newdata{'surname'});
312 if (C4::Context->preference("IndependentBranches")) {
313 unless ( C4::Context->IsSuperLibrarian() ){
314 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
315 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
316 push @errors, "ERROR_branch";
320 # Check if the 'userid' is unique. 'userid' might not always be present in
321 # the edited values list when editing certain sub-forms. Get it straight
322 # from the DB if absent.
323 my $userid = $newdata{ userid } // $borrower_data->{ userid };
324 unless (Check_Userid($userid,$borrowernumber)) {
325 push @errors, "ERROR_login_exist";
328 my $password = $input->param('password');
329 my $password2 = $input->param('password2');
330 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
331 push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
333 # Validate emails
334 my $emailprimary = $input->param('email');
335 my $emailsecondary = $input->param('emailpro');
336 my $emailalt = $input->param('B_email');
338 if ($emailprimary) {
339 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
341 if ($emailsecondary) {
342 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
344 if ($emailalt) {
345 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
348 if (C4::Context->preference('ExtendedPatronAttributes')) {
349 $extended_patron_attributes = parse_extended_patron_attributes($input);
350 foreach my $attr (@$extended_patron_attributes) {
351 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
352 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
353 push @errors, "ERROR_extended_unique_id_failed";
354 $template->param(
355 ERROR_extended_unique_id_failed_code => $attr->{code},
356 ERROR_extended_unique_id_failed_value => $attr->{value},
357 ERROR_extended_unique_id_failed_description => $attr_info->description()
364 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
365 unless ($newdata{'dateexpiry'}){
366 my $arg2 = $newdata{'dateenrolled'} || output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
367 $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
371 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
372 my $sms = $input->param('SMSnumber');
373 if ( defined $sms ) {
374 $newdata{smsalertnumber} = $sms;
377 ### Error checks should happen before this line.
378 $nok = $nok || scalar(@errors);
379 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
380 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
381 if ($op eq 'insert'){
382 # we know it's not a duplicate borrowernumber or there would already be an error
383 $borrowernumber = &AddMember(%newdata);
384 $newdata{'borrowernumber'} = $borrowernumber;
386 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
387 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
388 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
389 my $emailaddr;
390 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
391 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
392 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
394 elsif ($newdata{email} =~ /\w\@\w/) {
395 $emailaddr = $newdata{email}
397 elsif ($newdata{emailpro} =~ /\w\@\w/) {
398 $emailaddr = $newdata{emailpro}
400 elsif ($newdata{B_email} =~ /\w\@\w/) {
401 $emailaddr = $newdata{B_email}
403 # if we manage to find a valid email address, send notice
404 if ($emailaddr) {
405 $newdata{emailaddr} = $emailaddr;
406 my $err;
407 eval {
408 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
410 if ( $@ ) {
411 $template->param(error_alert => $@);
412 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
413 $template->{VARS}->{'error_alert'} = "no_email";
414 } else {
415 $template->{VARS}->{'info_alert'} = 1;
420 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
421 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
423 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
424 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
426 # Try to do the live sync with the Norwegian national patron database, if it is enabled
427 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
428 NLSync({ 'borrowernumber' => $borrowernumber });
430 } elsif ($op eq 'save'){
431 if ($NoUpdateLogin) {
432 delete $newdata{'password'};
433 delete $newdata{'userid'};
435 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
436 # updating any columns in the borrowers table,
437 # which can happen if we're only editing the
438 # patron attributes or messaging preferences sections
439 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
440 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
442 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
443 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
446 print scalar ($destination eq "circ") ?
447 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
448 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
449 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
452 if ($delete){
453 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
454 exit; # same as above
457 if ($nok or !$nodouble){
458 $op="add" if ($op eq "insert");
459 $op="modify" if ($op eq "save");
460 %data=%newdata;
461 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
462 unless ($step){
463 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
466 if (C4::Context->preference("IndependentBranches")) {
467 my $userenv = C4::Context->userenv;
468 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
469 unless ($userenv->{branch} eq $data{'branchcode'}){
470 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
471 exit;
475 if ($op eq 'add'){
476 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
478 if ($op eq "modify") {
479 $template->param( updtype => 'M',modify => 1 );
480 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
481 if ( $step == 4 ) {
482 $template->param( categorycode => $borrower_data->{'categorycode'} );
484 # Add sync data to the user data
485 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
486 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
487 if ( $sync ) {
488 $template->param(
489 sync => $sync->sync,
494 if ( $op eq "duplicate" ) {
495 $template->param( updtype => 'I' );
496 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
497 $data{'cardnumber'} = "";
500 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if ( ( $op eq 'add' ) or ( $op eq 'duplicate' ) );
501 if(!defined($data{'sex'})){
502 $template->param( none => 1);
503 } elsif($data{'sex'} eq 'F'){
504 $template->param( female => 1);
505 } elsif ($data{'sex'} eq 'M'){
506 $template->param( male => 1);
507 } else {
508 $template->param( none => 1);
511 ##Now all the data to modify a member.
513 my @typeloop;
514 my $no_categories = 1;
515 my $no_add;
516 foreach (qw(C A S P I X)) {
517 my $action="WHERE category_type=?";
518 my ($categories,$labels)=GetborCatFromCatType($_,$action);
519 if(scalar(@$categories) > 0){ $no_categories = 0; }
520 my @categoryloop;
521 foreach my $cat (@$categories){
522 push @categoryloop,{'categorycode' => $cat,
523 'categoryname' => $labels->{$cat},
524 'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) &&
525 $cat eq $borrower_data->{'categorycode'})
526 || (defined($categorycode) && $cat eq $categorycode)),
529 my %typehash;
530 $typehash{'typename'}=$_;
531 my $typedescription = "typename_".$typehash{'typename'};
532 $typehash{'categoryloop'}=\@categoryloop;
533 push @typeloop,{'typename' => $_,
534 $typedescription => 1,
535 'categoryloop' => \@categoryloop};
537 $template->param('typeloop' => \@typeloop,
538 no_categories => $no_categories);
539 if($no_categories){ $no_add = 1; }
540 # test in city
541 if ( $guarantorid ) {
542 $select_city = getidcity($data{city});
544 ($default_city=$select_city) if ($step eq 0);
545 if (!defined($select_city) or $select_city eq '' ){
546 $default_city = &getidcity($data{'city'});
549 my $city_arrayref = GetCities();
550 if (@{$city_arrayref} ) {
551 $template->param( city_cgipopup => 1);
553 if ($default_city) { # flag the current or default val
554 for my $city ( @{$city_arrayref} ) {
555 if ($default_city == $city->{cityid}) {
556 $city->{selected} = 1;
557 last;
563 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE', $data{streettype} );
564 $template->param( roadtypes => $roadtypes);
566 my $default_borrowertitle = '';
567 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
568 my($borrowertitle)=GetTitles();
569 $template->param( title_cgipopup => 1) if ($borrowertitle);
570 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
571 -id => 'btitle',
572 -values=>$borrowertitle,
573 -override => 1,
574 -default=>$default_borrowertitle
577 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
578 my @relshipdata;
579 while (@relationships) {
580 my $relship = shift @relationships || '';
581 my %row = ('relationship' => $relship);
582 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
583 $row{'selected'}=' selected';
584 } else {
585 $row{'selected'}='';
587 push(@relshipdata, \%row);
590 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
591 'lost' => ['lost']);
594 my @flagdata;
595 foreach (keys(%flags)) {
596 my $key = $_;
597 my %row = ('key' => $key,
598 'name' => $flags{$key}[0]);
599 if ($data{$key}) {
600 $row{'yes'}=' checked';
601 $row{'no'}='';
603 else {
604 $row{'yes'}='';
605 $row{'no'}=' checked';
607 push @flagdata,\%row;
610 # get Branch Loop
611 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
612 # in add mod: userbranch value come from branches table (ip correspondence)
614 my $userbranch = '';
615 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
616 $userbranch = C4::Context->userenv->{'branch'};
619 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
620 $userbranch = $data{'branchcode'};
623 my $branchloop = GetBranchesLoop( $userbranch );
625 if( !$branchloop ){
626 $no_add = 1;
627 $template->param(no_branches => 1);
629 if($no_categories){
630 $no_add = 1;
631 $template->param(no_categories => 1);
633 $template->param(no_add => $no_add);
634 # --------------------------------------------------------------------------------------------------------
636 $template->param( sort1 => $data{'sort1'});
637 $template->param( sort2 => $data{'sort2'});
639 if ($nok) {
640 foreach my $error (@errors) {
641 $template->param($error) || $template->param( $error => 1);
643 $template->param(nok => 1);
646 #Formatting data for display
648 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
649 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
651 if ( $op eq 'duplicate' ) {
652 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
653 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
655 if (C4::Context->preference('uppercasesurnames')) {
656 $data{'surname'} &&= uc( $data{'surname'} );
657 $data{'contactname'} &&= uc( $data{'contactname'} );
660 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
661 if ( $data{$_} ) {
662 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
664 $template->param( $_ => $data{$_});
667 if (C4::Context->preference('ExtendedPatronAttributes')) {
668 $template->param(ExtendedPatronAttributes => 1);
669 patron_attributes_form($template, $borrowernumber);
672 if (C4::Context->preference('EnhancedMessagingPreferences')) {
673 if ($op eq 'add') {
674 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
675 } else {
676 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
678 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
679 $template->param(SMSnumber => $data{'smsalertnumber'} );
680 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
683 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
684 $debug and warn "memberentry step: $step";
685 $template->param(%data);
686 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
687 $template->param( step => $step ) if $step; # associate with step to know where u are
689 $template->param(
690 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
691 category_type => $category_type,#to know the category type of the borrower
692 select_city => $select_city,
693 "$category_type" => 1,# associate with step to know where u are
694 destination => $destination,#to know wher u come from and wher u must go in redirect
695 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
696 "op$op" => 1);
698 $template->param( branchloop => $branchloop ) if ( $branchloop );
699 $template->param(
700 nodouble => $nodouble,
701 borrowernumber => $borrowernumber, #register number
702 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
703 relshiploop => \@relshipdata,
704 city_loop => $city_arrayref,
705 borrotitlepopup => $borrotitlepopup,
706 guarantorinfo => $guarantorinfo,
707 flagloop => \@flagdata,
708 category_type =>$category_type,
709 modify => $modify,
710 nok => $nok,#flag to know if an error
711 NoUpdateLogin => $NoUpdateLogin
714 if(defined($data{'flags'})){
715 $template->param(flags=>$data{'flags'});
717 if(defined($data{'contacttitle'})){
718 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
722 my ( $min, $max ) = C4::Members::get_cardnumber_length();
723 if ( defined $min ) {
724 $template->param(
725 minlength_cardnumber => $min,
726 maxlength_cardnumber => $max
730 output_html_with_http_headers $input, $cookie, $template->output;
732 sub parse_extended_patron_attributes {
733 my ($input) = @_;
734 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->param();
736 my @attr = ();
737 my %dups = ();
738 foreach my $key (@patron_attr) {
739 my $value = $input->param($key);
740 next unless defined($value) and $value ne '';
741 my $password = $input->param("${key}_password");
742 my $code = $input->param("${key}_code");
743 next if exists $dups{$code}->{$value};
744 $dups{$code}->{$value} = 1;
745 push @attr, { code => $code, value => $value, password => $password };
747 return \@attr;
750 sub patron_attributes_form {
751 my $template = shift;
752 my $borrowernumber = shift;
754 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
755 if (scalar(@types) == 0) {
756 $template->param(no_patron_attribute_types => 1);
757 return;
759 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
760 my @classes = uniq( map {$_->{class}} @$attributes );
761 @classes = sort @classes;
763 # map patron's attributes into a more convenient structure
764 my %attr_hash = ();
765 foreach my $attr (@$attributes) {
766 push @{ $attr_hash{$attr->{code}} }, $attr;
769 my @attribute_loop = ();
770 my $i = 0;
771 my %items_by_class;
772 foreach my $type_code (map { $_->{code} } @types) {
773 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
774 my $entry = {
775 class => $attr_type->class(),
776 code => $attr_type->code(),
777 description => $attr_type->description(),
778 repeatable => $attr_type->repeatable(),
779 password_allowed => $attr_type->password_allowed(),
780 category => $attr_type->authorised_value_category(),
781 category_code => $attr_type->category_code(),
782 password => '',
784 if (exists $attr_hash{$attr_type->code()}) {
785 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
786 my $newentry = { %$entry };
787 $newentry->{value} = $attr->{value};
788 $newentry->{password} = $attr->{password};
789 $newentry->{use_dropdown} = 0;
790 if ($attr_type->authorised_value_category()) {
791 $newentry->{use_dropdown} = 1;
792 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
794 $i++;
795 $newentry->{form_id} = "patron_attr_$i";
796 push @{$items_by_class{$attr_type->class()}}, $newentry;
798 } else {
799 $i++;
800 my $newentry = { %$entry };
801 if ($attr_type->authorised_value_category()) {
802 $newentry->{use_dropdown} = 1;
803 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
805 $newentry->{form_id} = "patron_attr_$i";
806 push @{$items_by_class{$attr_type->class()}}, $newentry;
809 while ( my ($class, @items) = each %items_by_class ) {
810 my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
811 push @attribute_loop, {
812 class => $class,
813 items => @items,
814 lib => $lib,
818 $template->param(patron_attributes => \@attribute_loop);
822 # Local Variables:
823 # tab-width: 8
824 # End: