Bug 10021: Remove accountlines columns - DBIC Schema changes
[koha.git] / members / memberentry.pl
blob13793e71cf0550f585cb12d950b2f20cb4ac503c
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::AuthUtils;
41 use Koha::AuthorisedValues;
42 use Koha::Patron::Debarments;
43 use Koha::Cities;
44 use Koha::DateUtils;
45 use Koha::Libraries;
46 use Koha::Patrons;
47 use Koha::Patron::Categories;
48 use Koha::Patron::HouseboundRole;
49 use Koha::Patron::HouseboundRoles;
50 use Koha::Token;
51 use Email::Valid;
52 use Module::Load;
53 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
54 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
56 use Koha::SMS::Providers;
58 use vars qw($debug);
60 BEGIN {
61 $debug = $ENV{DEBUG} || 0;
64 my $input = new CGI;
65 ($debug) or $debug = $input->param('debug') || 0;
66 my %data;
68 my $dbh = C4::Context->dbh;
70 my ($template, $loggedinuser, $cookie)
71 = get_template_and_user({template_name => "members/memberentrygen.tt",
72 query => $input,
73 type => "intranet",
74 authnotrequired => 0,
75 flagsrequired => {borrowers => 1},
76 debug => ($debug) ? 1 : 0,
77 });
79 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
80 my @providers = Koha::SMS::Providers->search();
81 $template->param( sms_providers => \@providers );
84 my $guarantorid = $input->param('guarantorid');
85 my $borrowernumber = $input->param('borrowernumber');
86 my $actionType = $input->param('actionType') || '';
87 my $modify = $input->param('modify');
88 my $delete = $input->param('delete');
89 my $op = $input->param('op');
90 my $destination = $input->param('destination');
91 my $cardnumber = $input->param('cardnumber');
92 my $check_member = $input->param('check_member');
93 my $nodouble = $input->param('nodouble');
94 my $duplicate = $input->param('duplicate');
95 my $quickadd = $input->param('quickadd');
96 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
97 # modifying an existing patron, it ipso facto
98 # isn't a duplicate. Marking FIXME because this
99 # script needs to be refactored.
100 my $nok = $input->param('nok');
101 my $guarantorinfo = $input->param('guarantorinfo');
102 my $step = $input->param('step') || 0;
103 my @errors;
104 my $borrower_data;
105 my $NoUpdateLogin;
106 my $userenv = C4::Context->userenv;
109 ## Deal with debarments
110 $template->param(
111 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
112 my @debarments_to_remove = $input->multi_param('remove_debarment');
113 foreach my $d ( @debarments_to_remove ) {
114 DelDebarment( $d );
116 if ( $input->param('add_debarment') ) {
118 my $expiration = $input->param('debarred_expiration');
119 $expiration =
120 $expiration
121 ? output_pref(
122 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
123 : undef;
125 AddDebarment(
127 borrowernumber => $borrowernumber,
128 type => 'MANUAL',
129 comment => scalar $input->param('debarred_comment'),
130 expiration => $expiration,
135 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
137 # function to designate mandatory fields (visually with css)
138 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
139 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
140 foreach (@field_check) {
141 $template->param( "mandatory$_" => 1);
143 # function to designate unwanted fields
144 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
145 @field_check=split(/\|/,$check_BorrowerUnwantedField);
146 foreach (@field_check) {
147 next unless m/\w/o;
148 $template->param( "no$_" => 1);
150 $template->param( "add" => 1 ) if ( $op eq 'add' );
151 $template->param( "quickadd" => 1 ) if ( $quickadd );
152 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
153 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
154 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
155 my $patron = Koha::Patrons->find( $borrowernumber );
156 unless ( $patron ) {
157 print $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber");
158 exit;
161 $borrower_data = $patron->unblessed;
162 $borrower_data->{category_type} = $patron->category->category_type;
164 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
165 my $category_type = $input->param('category_type') || '';
166 unless ($category_type or !($categorycode)){
167 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
168 $category_type = $borrowercategory->category_type;
169 my $category_name = $borrowercategory->description;
170 $template->param("categoryname"=>$category_name);
172 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
174 # if a add or modify is requested => check validity of data.
175 %data = %$borrower_data if ($borrower_data);
177 # initialize %newdata
178 my %newdata; # comes from $input->param()
179 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
180 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
181 foreach my $key (@names) {
182 if (defined $input->param($key)) {
183 $newdata{$key} = $input->param($key);
184 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
188 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
189 next unless exists $newdata{$_};
190 my $userdate = $newdata{$_} or next;
192 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
193 if ( $formatteddate ) {
194 $newdata{$_} = $formatteddate;
195 } else {
196 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
197 $template->param( "ERROR_$_" => 1 );
198 push(@errors,"ERROR_$_");
201 # check permission to modify login info.
202 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
203 $NoUpdateLogin = 1;
207 # remove keys from %newdata that ModMember() doesn't like
209 my @keys_to_delete = (
210 qr/^BorrowerMandatoryField$/,
211 qr/^category_type$/,
212 qr/^check_member$/,
213 qr/^destination$/,
214 qr/^nodouble$/,
215 qr/^op$/,
216 qr/^save$/,
217 qr/^updtype$/,
218 qr/^SMSnumber$/,
219 qr/^setting_extended_patron_attributes$/,
220 qr/^setting_messaging_prefs$/,
221 qr/^digest$/,
222 qr/^modify$/,
223 qr/^step$/,
224 qr/^\d+$/,
225 qr/^\d+-DAYS/,
226 qr/^patron_attr_/,
228 for my $regexp (@keys_to_delete) {
229 for (keys %newdata) {
230 delete($newdata{$_}) if /$regexp/;
235 # Test uniqueness of surname, firstname and dateofbirth
236 if ( ( $op eq 'insert' ) and !$nodouble ) {
237 my $conditions;
238 $conditions->{surname} = $newdata{surname} if $newdata{surname};
239 if ( $category_type ne 'I' ) {
240 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
241 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
243 $nodouble = 1;
244 my $patrons = Koha::Patrons->search($conditions);
245 if ( $patrons->count > 0) {
246 $nodouble = 0;
247 $check_member = $patrons->next->borrowernumber;
251 #recover all data from guarantor address phone ,fax...
252 if ( $guarantorid ) {
253 if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
254 my $guarantordata = $guarantor->unblessed;
255 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
256 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
257 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
258 $newdata{'contactname'} = $guarantordata->{'surname'};
259 $newdata{'contacttitle'} = $guarantordata->{'title'};
260 if ( $op eq 'add' ) {
261 foreach (qw(streetnumber address streettype address2
262 zipcode country city state phone phonepro mobile fax email emailpro branchcode
263 B_streetnumber B_streettype B_address B_address2
264 B_city B_state B_zipcode B_country B_email B_phone)) {
265 $newdata{$_} = $guarantordata->{$_};
271 ###############test to take the right zipcode, country and city name ##############
272 # set only if parameter was passed from the form
273 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
274 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
275 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
277 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
279 # builds default userid
280 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
281 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
282 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
283 # Full page edit, firstname and surname input zones are present
284 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
286 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
287 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
288 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
289 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
291 else {
292 $newdata{'userid'} = $data{'userid'};
296 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
297 my $extended_patron_attributes = ();
298 if ($op eq 'save' || $op eq 'insert'){
300 die "Wrong CSRF token"
301 unless Koha::Token->new->check_csrf({
302 session_id => scalar $input->cookie('CGISESSID'),
303 token => scalar $input->param('csrf_token'),
306 # If the cardnumber is blank, treat it as null.
307 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
309 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
310 push @errors, $error_code == 1
311 ? 'ERROR_cardnumber_already_exists'
312 : $error_code == 2
313 ? 'ERROR_cardnumber_length'
314 : ()
317 my $dateofbirth;
318 if ($op eq 'save' && $step == 3) {
319 my $patron = Koha::Patrons->find( $borrowernumber );
320 $dateofbirth = $patron->dateofbirth;
322 else {
323 $dateofbirth = $newdata{dateofbirth};
326 if ( $dateofbirth ) {
327 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
328 my $age = $patron->get_age;
329 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
330 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
331 if (($high && ($age > $high)) or ($age < $low)) {
332 push @errors, 'ERROR_age_limitations';
333 $template->param( age_low => $low);
334 $template->param( age_high => $high);
338 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
339 $newdata{'surname'} = uc($newdata{'surname'});
342 if (C4::Context->preference("IndependentBranches")) {
343 unless ( C4::Context->IsSuperLibrarian() ){
344 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
345 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
346 push @errors, "ERROR_branch";
350 # Check if the 'userid' is unique. 'userid' might not always be present in
351 # the edited values list when editing certain sub-forms. Get it straight
352 # from the DB if absent.
353 my $userid = $newdata{ userid } // $borrower_data->{ userid };
354 unless (Check_Userid($userid,$borrowernumber)) {
355 push @errors, "ERROR_login_exist";
358 my $password = $input->param('password');
359 my $password2 = $input->param('password2');
360 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
362 if ( $password and $password ne '****' ) {
363 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
364 unless ( $is_valid ) {
365 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
366 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
367 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
371 # Validate emails
372 my $emailprimary = $input->param('email');
373 my $emailsecondary = $input->param('emailpro');
374 my $emailalt = $input->param('B_email');
376 if ($emailprimary) {
377 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
379 if ($emailsecondary) {
380 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
382 if ($emailalt) {
383 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
386 if (C4::Context->preference('ExtendedPatronAttributes')) {
387 $extended_patron_attributes = parse_extended_patron_attributes($input);
388 foreach my $attr (@$extended_patron_attributes) {
389 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
390 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
391 push @errors, "ERROR_extended_unique_id_failed";
392 $template->param(
393 ERROR_extended_unique_id_failed_code => $attr->{code},
394 ERROR_extended_unique_id_failed_value => $attr->{value},
395 ERROR_extended_unique_id_failed_description => $attr_info->description()
402 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
403 unless ($newdata{'dateexpiry'}){
404 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
405 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
409 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
410 my $sms = $input->param('SMSnumber');
411 if ( defined $sms ) {
412 $newdata{smsalertnumber} = $sms;
415 ### Error checks should happen before this line.
416 $nok = $nok || scalar(@errors);
417 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
418 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
419 if ($op eq 'insert'){
420 # we know it's not a duplicate borrowernumber or there would already be an error
421 $borrowernumber = &AddMember(%newdata);
422 $newdata{'borrowernumber'} = $borrowernumber;
424 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
425 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
426 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
427 my $emailaddr;
428 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
429 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
430 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
432 elsif ($newdata{email} =~ /\w\@\w/) {
433 $emailaddr = $newdata{email}
435 elsif ($newdata{emailpro} =~ /\w\@\w/) {
436 $emailaddr = $newdata{emailpro}
438 elsif ($newdata{B_email} =~ /\w\@\w/) {
439 $emailaddr = $newdata{B_email}
441 # if we manage to find a valid email address, send notice
442 if ($emailaddr) {
443 $newdata{emailaddr} = $emailaddr;
444 my $err;
445 eval {
446 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
448 if ( $@ ) {
449 $template->param(error_alert => $@);
450 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
451 $template->{VARS}->{'error_alert'} = "no_email";
452 } else {
453 $template->{VARS}->{'info_alert'} = 1;
458 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
459 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
461 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
462 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
464 # Try to do the live sync with the Norwegian national patron database, if it is enabled
465 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
466 NLSync({ 'borrowernumber' => $borrowernumber });
469 # Create HouseboundRole if necessary.
470 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
471 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
472 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
473 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
474 # Only create a HouseboundRole if patron has a role.
475 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
476 Koha::Patron::HouseboundRole->new({
477 borrowernumber_id => $borrowernumber,
478 housebound_chooser => $hsbnd_chooser,
479 housebound_deliverer => $hsbnd_deliverer,
480 })->store;
483 } elsif ($op eq 'save') {
485 # Update or create our HouseboundRole if necessary.
486 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
487 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
488 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
489 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
490 if ( $housebound_role ) {
491 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
492 # Update our HouseboundRole.
493 $housebound_role
494 ->housebound_chooser($hsbnd_chooser)
495 ->housebound_deliverer($hsbnd_deliverer)
496 ->store;
497 } else {
498 $housebound_role->delete; # No longer needed.
500 } else {
501 # Only create a HouseboundRole if patron has a role.
502 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
503 $housebound_role = Koha::Patron::HouseboundRole->new({
504 borrowernumber_id => $borrowernumber,
505 housebound_chooser => $hsbnd_chooser,
506 housebound_deliverer => $hsbnd_deliverer,
507 })->store;
511 if ($NoUpdateLogin) {
512 delete $newdata{'password'};
513 delete $newdata{'userid'};
515 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
516 # updating any columns in the borrowers table,
517 # which can happen if we're only editing the
518 # patron attributes or messaging preferences sections
519 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
520 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
522 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
523 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
527 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
528 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
529 $destination = 'not_circ';
531 print scalar( $destination eq "circ" )
532 ? $input->redirect(
533 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
534 : $input->redirect(
535 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
537 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
540 if ($delete){
541 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
542 exit; # same as above
545 if ($nok or !$nodouble){
546 $op="add" if ($op eq "insert");
547 $op="modify" if ($op eq "save");
548 %data=%newdata;
549 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
550 unless ($step){
551 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
554 if (C4::Context->preference("IndependentBranches")) {
555 my $userenv = C4::Context->userenv;
556 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
557 unless ($userenv->{branch} eq $data{'branchcode'}){
558 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
559 exit;
563 if ($op eq 'add'){
564 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
566 if ($op eq "modify") {
567 $template->param( updtype => 'M',modify => 1 );
568 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
569 if ( $step == 4 ) {
570 $template->param( categorycode => $borrower_data->{'categorycode'} );
572 # Add sync data to the user data
573 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
574 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
575 if ( $sync ) {
576 $template->param(
577 sync => $sync->sync,
582 if ( $op eq "duplicate" ) {
583 $template->param( updtype => 'I' );
584 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
585 $data{'cardnumber'} = "";
588 if(!defined($data{'sex'})){
589 $template->param( none => 1);
590 } elsif($data{'sex'} eq 'F'){
591 $template->param( female => 1);
592 } elsif ($data{'sex'} eq 'M'){
593 $template->param( male => 1);
594 } else {
595 $template->param( none => 1);
598 ##Now all the data to modify a member.
600 my @typeloop;
601 my $no_categories = 1;
602 my $no_add;
603 foreach my $category_type (qw(C A S P I X)) {
604 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
605 $no_categories = 0 if $patron_categories->count > 0;
607 my @categoryloop;
608 while ( my $patron_category = $patron_categories->next ) {
609 push @categoryloop,
610 { 'categorycode' => $patron_category->categorycode,
611 'categoryname' => $patron_category->description,
612 'categorycodeselected' =>
613 ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
616 my %typehash;
617 $typehash{'typename'} = $category_type;
618 my $typedescription = "typename_" . $typehash{'typename'};
619 $typehash{'categoryloop'} = \@categoryloop;
620 push @typeloop,
621 { 'typename' => $category_type,
622 $typedescription => 1,
623 'categoryloop' => \@categoryloop
627 $template->param('typeloop' => \@typeloop,
628 no_categories => $no_categories);
629 if($no_categories){ $no_add = 1; }
632 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
633 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
634 $template->param(
635 roadtypes => $roadtypes,
636 cities => $cities,
639 my $default_borrowertitle = '';
640 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
642 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
643 my @relshipdata;
644 while (@relationships) {
645 my $relship = shift @relationships || '';
646 my %row = ('relationship' => $relship);
647 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
648 $row{'selected'}=' selected';
649 } else {
650 $row{'selected'}='';
652 push(@relshipdata, \%row);
655 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
656 'lost' => ['lost']);
659 my @flagdata;
660 foreach (keys(%flags)) {
661 my $key = $_;
662 my %row = ('key' => $key,
663 'name' => $flags{$key}[0]);
664 if ($data{$key}) {
665 $row{'yes'}=' checked';
666 $row{'no'}='';
668 else {
669 $row{'yes'}='';
670 $row{'no'}=' checked';
672 push @flagdata,\%row;
675 # get Branch Loop
676 # in modify mod: userbranch value comes from borrowers table
677 # in add mod: userbranch value comes from branches table (ip correspondence)
679 my $userbranch = '';
680 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
681 $userbranch = C4::Context->userenv->{'branch'};
684 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
685 $userbranch = $data{'branchcode'};
687 $template->param( userbranch => $userbranch );
689 if ( Koha::Libraries->search->count < 1 ){
690 $no_add = 1;
691 $template->param(no_branches => 1);
693 if($no_categories){
694 $no_add = 1;
695 $template->param(no_categories => 1);
697 $template->param(no_add => $no_add);
698 # --------------------------------------------------------------------------------------------------------
700 $template->param( sort1 => $data{'sort1'});
701 $template->param( sort2 => $data{'sort2'});
703 if ($nok) {
704 foreach my $error (@errors) {
705 $template->param($error) || $template->param( $error => 1);
707 $template->param(nok => 1);
710 #Formatting data for display
712 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
713 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
715 if ( $op eq 'duplicate' ) {
716 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
717 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
718 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
720 if (C4::Context->preference('uppercasesurnames')) {
721 $data{'surname'} &&= uc( $data{'surname'} );
722 $data{'contactname'} &&= uc( $data{'contactname'} );
725 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
726 if ( $data{$_} ) {
727 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
729 $template->param( $_ => $data{$_});
732 if (C4::Context->preference('ExtendedPatronAttributes')) {
733 $template->param(ExtendedPatronAttributes => 1);
734 patron_attributes_form($template, $borrowernumber);
737 if (C4::Context->preference('EnhancedMessagingPreferences')) {
738 if ($op eq 'add') {
739 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
740 } else {
741 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
743 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
744 $template->param(SMSnumber => $data{'smsalertnumber'} );
745 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
748 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
749 $debug and warn "memberentry step: $step";
750 $template->param(%data);
751 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
752 $template->param( step => $step ) if $step; # associate with step to know where u are
754 $template->param(
755 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
756 category_type => $category_type,#to know the category type of the borrower
757 "$category_type" => 1,# associate with step to know where u are
758 destination => $destination,#to know wher u come from and wher u must go in redirect
759 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
760 "op$op" => 1);
762 $template->param(
763 nodouble => $nodouble,
764 borrowernumber => $borrowernumber, #register number
765 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
766 relshiploop => \@relshipdata,
767 btitle=> $default_borrowertitle,
768 guarantorinfo => $guarantorinfo,
769 flagloop => \@flagdata,
770 category_type =>$category_type,
771 modify => $modify,
772 nok => $nok,#flag to know if an error
773 NoUpdateLogin => $NoUpdateLogin,
776 # Generate CSRF token
777 $template->param( csrf_token =>
778 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
781 # HouseboundModule data
782 $template->param(
783 housebound_role => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
786 if(defined($data{'flags'})){
787 $template->param(flags=>$data{'flags'});
789 if(defined($data{'contacttitle'})){
790 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
794 my ( $min, $max ) = C4::Members::get_cardnumber_length();
795 if ( defined $min ) {
796 $template->param(
797 minlength_cardnumber => $min,
798 maxlength_cardnumber => $max
802 if ( C4::Context->preference('TranslateNotices') ) {
803 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
804 $template->param( languages => $translated_languages );
807 output_html_with_http_headers $input, $cookie, $template->output;
809 sub parse_extended_patron_attributes {
810 my ($input) = @_;
811 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
813 my @attr = ();
814 my %dups = ();
815 foreach my $key (@patron_attr) {
816 my $value = $input->param($key);
817 next unless defined($value) and $value ne '';
818 my $code = $input->param("${key}_code");
819 next if exists $dups{$code}->{$value};
820 $dups{$code}->{$value} = 1;
821 push @attr, { code => $code, value => $value };
823 return \@attr;
826 sub patron_attributes_form {
827 my $template = shift;
828 my $borrowernumber = shift;
830 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
831 if (scalar(@types) == 0) {
832 $template->param(no_patron_attribute_types => 1);
833 return;
835 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
836 my @classes = uniq( map {$_->{class}} @$attributes );
837 @classes = sort @classes;
839 # map patron's attributes into a more convenient structure
840 my %attr_hash = ();
841 foreach my $attr (@$attributes) {
842 push @{ $attr_hash{$attr->{code}} }, $attr;
845 my @attribute_loop = ();
846 my $i = 0;
847 my %items_by_class;
848 foreach my $type_code (map { $_->{code} } @types) {
849 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
850 my $entry = {
851 class => $attr_type->class(),
852 code => $attr_type->code(),
853 description => $attr_type->description(),
854 repeatable => $attr_type->repeatable(),
855 category => $attr_type->authorised_value_category(),
856 category_code => $attr_type->category_code(),
858 if (exists $attr_hash{$attr_type->code()}) {
859 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
860 my $newentry = { %$entry };
861 $newentry->{value} = $attr->{value};
862 $newentry->{use_dropdown} = 0;
863 if ($attr_type->authorised_value_category()) {
864 $newentry->{use_dropdown} = 1;
865 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
867 $i++;
868 $newentry->{form_id} = "patron_attr_$i";
869 push @{$items_by_class{$attr_type->class()}}, $newentry;
871 } else {
872 $i++;
873 my $newentry = { %$entry };
874 if ($attr_type->authorised_value_category()) {
875 $newentry->{use_dropdown} = 1;
876 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
878 $newentry->{form_id} = "patron_attr_$i";
879 push @{$items_by_class{$attr_type->class()}}, $newentry;
882 while ( my ($class, @items) = each %items_by_class ) {
883 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
884 my $lib = $av->count ? $av->next->lib : $class;
885 push @attribute_loop, {
886 class => $class,
887 items => @items,
888 lib => $lib,
892 $template->param(patron_attributes => \@attribute_loop);
896 # Local Variables:
897 # tab-width: 8
898 # End: