Bug 22359: Improvements to payment collection inputs
[koha-ffzg.git] / members / memberentry.pl
index 2bf1a02..902beeb 100755 (executable)
@@ -48,10 +48,6 @@ use Koha::Patron::HouseboundRole;
 use Koha::Patron::HouseboundRoles;
 use Koha::Token;
 use Email::Valid;
-use Module::Load;
-if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
-    load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
-}
 use Koha::SMS::Providers;
 
 use vars qw($debug);
@@ -87,7 +83,6 @@ if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
     $template->param( sms_providers => \@providers );
 }
 
-my $guarantorid    = $input->param('guarantorid');
 my $actionType     = $input->param('actionType') || '';
 my $modify         = $input->param('modify');
 my $delete         = $input->param('delete');
@@ -103,13 +98,26 @@ $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to rep
                                      # isn't a duplicate.  Marking FIXME because this
                                      # script needs to be refactored.
 my $nok           = $input->param('nok');
-my $guarantorinfo = $input->param('guarantorinfo');
 my $step          = $input->param('step') || 0;
 my @errors;
 my $borrower_data;
 my $NoUpdateLogin;
 my $userenv = C4::Context->userenv;
 
+## Deal with guarantor stuff
+$template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
+
+my $guarantor_id = $input->param('guarantor_id');
+my $guarantor = undef;
+$guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
+$template->param( guarantor => $guarantor );
+
+my @delete_guarantor = $input->multi_param('delete_guarantor');
+foreach my $id ( @delete_guarantor ) {
+    my $r = Koha::Patron::Relationships->find( $id );
+    $r->delete() if $r;
+}
+
 ## Deal with debarments
 $template->param(
     debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
@@ -141,28 +149,27 @@ $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnam
 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
 foreach (@field_check) {
-       $template->param( "mandatory$_" => 1);    
+    $template->param( "mandatory$_" => 1 );
 }
 # function to designate unwanted fields
 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
 @field_check=split(/\|/,$check_BorrowerUnwantedField);
 foreach (@field_check) {
     next unless m/\w/o;
-       $template->param( "no$_" => 1);
+    $template->param( "no$_" => 1 );
 }
 $template->param( "add" => 1 ) if ( $op eq 'add' );
 $template->param( "quickadd" => 1 ) if ( $quickadd );
 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
-    my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
+    my $logged_in_user = Koha::Patrons->find( $loggedinuser );
     output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
 
     $borrower_data = $patron->unblessed;
     $borrower_data->{category_type} = $patron->category->category_type;
-} else {
-    $patron = Koha::Patron->new;
 }
+
 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
 my $category_type = $input->param('category_type') || '';
 unless ($category_type or !($categorycode)){
@@ -183,7 +190,6 @@ if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' )
     foreach my $key (@names) {
         if (defined $input->param($key)) {
             $newdata{$key} = $input->param($key);
-            $newdata{$key} =~ s/\"/"/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
         }
     }
 
@@ -227,9 +233,13 @@ if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' )
         qr/^\d+-DAYS/,
         qr/^patron_attr_/,
         qr/^csrf_token$/,
-        qr/^add_debarment$/, qr/^debarred_expiration$/, # We already dealt with debarments previously
+        qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
         qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
         qr/^select_city$/,
+        qr/^new_guarantor_/,
+        qr/^guarantor_firstname$/,
+        qr/^guarantor_surname$/,
+        qr/^delete_guarantor$/,
     );
     for my $regexp (@keys_to_delete) {
         for (keys %newdata) {
@@ -251,26 +261,19 @@ if ( ( $op eq 'insert' ) and !$nodouble ) {
     if ( $patrons->count > 0) {
         $nodouble = 0;
         $check_member = $patrons->next->borrowernumber;
-    }
-}
 
-  #recover all data from guarantor address phone ,fax... 
-if ( $guarantorid ) {
-    if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
-        my $guarantordata = $guarantor->unblessed;
-        $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
-        $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
-        $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
-        $newdata{'contactname'}     = $guarantordata->{'surname'};
-        $newdata{'contacttitle'}    = $guarantordata->{'title'};
-        if ( $op eq 'add' ) {
-               foreach (qw(streetnumber address streettype address2
-                        zipcode country city state phone phonepro mobile fax email emailpro branchcode
-                        B_streetnumber B_streettype B_address B_address2
-                        B_city B_state B_zipcode B_country B_email B_phone)) {
-                       $newdata{$_} = $guarantordata->{$_};
-               }
+
+        my @new_guarantors;
+        my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
+        my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
+        foreach my $gid ( @new_guarantor_id ) {
+            my $patron = Koha::Patrons->find( $gid );
+            my $relationship = shift( @new_guarantor_relationship );
+            next unless $patron;
+            my $g = { patron => $patron, relationship => $relationship };
+            push( @new_guarantors, $g );
         }
+        $template->param( new_guarantors => \@new_guarantors );
     }
 }
 
@@ -285,21 +288,23 @@ $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'))
 # builds default userid
 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
+    my $fake_patron = Koha::Patron->new;
+    $fake_patron->userid($patron->userid) if $patron; # editing
     if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
         # Full page edit, firstname and surname input zones are present
-        $patron->firstname($newdata{firstname});
-        $patron->surname($newdata{surname});
-        $patron->generate_userid;
-        $newdata{'userid'} = $patron->userid;
+        $fake_patron->firstname($newdata{firstname});
+        $fake_patron->surname($newdata{surname});
+        $fake_patron->generate_userid;
+        $newdata{'userid'} = $fake_patron->userid;
     }
     elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
         # FIXME clean thiscode newdata vs data is very confusing
-        $patron->firstname($data{firstname});
-        $patron->surname($data{surname});
-        $patron->generate_userid;
-        $newdata{'userid'} = $patron->userid;
+        $fake_patron->firstname($data{firstname});
+        $fake_patron->surname($data{surname});
+        $fake_patron->generate_userid;
+        $newdata{'userid'} = $fake_patron->userid;
     }
     else {
         $newdata{'userid'} = $data{'userid'};
@@ -310,7 +315,7 @@ $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled
 my $extended_patron_attributes = ();
 if ($op eq 'save' || $op eq 'insert'){
 
-    die "Wrong CSRF token"
+    output_and_exit( $input, $cookie, $template,  'wrong_csrf_token' )
         unless Koha::Token->new->check_csrf({
             session_id => scalar $input->cookie('CGISESSID'),
             token  => scalar $input->param('csrf_token'),
@@ -347,10 +352,6 @@ if ($op eq 'save' || $op eq 'insert'){
         }
     }
   
-    if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
-        $newdata{'surname'} = uc($newdata{'surname'});
-    }
-
   if (C4::Context->preference("IndependentBranches")) {
     unless ( C4::Context->IsSuperLibrarian() ){
       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
@@ -439,7 +440,9 @@ if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
             # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
             warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
         } else {
+            add_guarantors( $patron, $input );
             $borrowernumber = $patron->borrowernumber;
+            $newdata{'borrowernumber'} = $borrowernumber;
         }
 
         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
@@ -482,10 +485,6 @@ if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
         }
-        # Try to do the live sync with the Norwegian national patron database, if it is enabled
-        if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
-            NLSync({ 'borrowernumber' => $borrowernumber });
-        }
 
         # Create HouseboundRole if necessary.
         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
@@ -543,8 +542,13 @@ if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
                                                                 # which can happen if we're only editing the
                                                                 # patron attributes or messaging preferences sections
 
-        $patron->update_password($newdata{userid}, $newdata{password});
+        # should never raise an exception as password validity is checked above
+        my $password = $newdata{password};
+        if ( $password and $password ne '****' ) {
+            $patron->set_password({ password => $password });
+        }
 
+        add_guarantors( $patron, $input );
         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
         }
@@ -598,15 +602,6 @@ if ($op eq "modify")  {
     if ( $step == 4 ) {
         $template->param( categorycode => $borrower_data->{'categorycode'} );
     }
-    # Add sync data to the user data
-    if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
-        my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
-        if ( $sync ) {
-            $template->param(
-                sync => $sync->sync,
-            );
-        }
-    }
 }
 if ( $op eq "duplicate" ) {
     $template->param( updtype => 'I' );
@@ -652,11 +647,10 @@ foreach my $category_type (qw(C A S P I X)) {
         'categoryloop'   => \@categoryloop
       };
 }
-
-$template->param('typeloop' => \@typeloop,
-        no_categories => $no_categories);
-if($no_categories){ $no_add = 1; }
-
+$template->param(
+    typeloop      => \@typeloop,
+    no_categories => $no_categories,
+);
 
 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
@@ -681,24 +675,27 @@ while (@relationships) {
   push(@relshipdata, \%row);
 }
 
-my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
-        'lost'          => ['lost']);
+my %flags = (
+    'gonenoaddress' => ['gonenoaddress'],
+    'lost'          => ['lost']
+);
 
 my @flagdata;
-foreach (keys(%flags)) {
-       my $key = $_;
-       my %row =  ('key'   => $key,
-                   'name'  => $flags{$key}[0]);
-       if ($data{$key}) {
-               $row{'yes'}=' checked';
-               $row{'no'}='';
+foreach ( keys(%flags) ) {
+    my $key = $_;
+    my %row = (
+        'key'  => $key,
+        'name' => $flags{$key}[0]
+    );
+    if ( $data{$key} ) {
+        $row{'yes'} = ' checked';
+        $row{'no'}  = '';
     }
-       else {
-               $row{'yes'}='';
-               $row{'no'}=' checked';
-       }
-       push @flagdata,\%row;
+    else {
+        $row{'yes'} = '';
+        $row{'no'}  = ' checked';
+    }
+    push @flagdata, \%row;
 }
 
 # get Branch Loop
@@ -759,8 +756,7 @@ foreach (qw(dateenrolled dateexpiry dateofbirth)) {
 }
 
 if (C4::Context->preference('ExtendedPatronAttributes')) {
-    $template->param(ExtendedPatronAttributes => 1);
-    patron_attributes_form($template, $borrowernumber);
+    patron_attributes_form($template, $borrowernumber, $op);
 }
 
 if (C4::Context->preference('EnhancedMessagingPreferences')) {
@@ -774,7 +770,7 @@ if (C4::Context->preference('EnhancedMessagingPreferences')) {
     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
 }
 
-$template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
+$template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
 $debug and warn "memberentry step: $step";
 $template->param(%data);
 $template->param( "step_$step"  => 1) if $step;        # associate with step to know where u are
@@ -788,17 +784,12 @@ $template->param(
   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
   "op$op"   => 1);
 
-$guarantorid = $borrower_data->{'guarantorid'} || $guarantorid;
-my $guarantor = $guarantorid ? Koha::Patrons->find( $guarantorid ) : undef;
 $template->param(
-  patron => $patron, # Used by address include templates now
+  patron => $patron ? $patron : \%newdata, # Used by address include templates now
   nodouble  => $nodouble,
   borrowernumber  => $borrowernumber, #register number
-  guarantor   => $guarantor,
-  guarantorid => $guarantorid,
   relshiploop => \@relshipdata,
   btitle=> $default_borrowertitle,
-  guarantorinfo   => $guarantorinfo,
   flagloop  => \@flagdata,
   category_type =>$category_type,
   modify          => $modify,
@@ -813,7 +804,7 @@ $template->param( csrf_token =>
 
 # HouseboundModule data
 $template->param(
-    housebound_role  => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
+    housebound_role  => Koha::Patron::HouseboundRoles->find($borrowernumber),
 );
 
 if(defined($data{'flags'})){
@@ -859,6 +850,7 @@ sub  parse_extended_patron_attributes {
 sub patron_attributes_form {
     my $template = shift;
     my $borrowernumber = shift;
+    my $op = shift;
 
     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
     if (scalar(@types) == 0) {
@@ -898,6 +890,7 @@ sub patron_attributes_form {
                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
                 }
                 $i++;
+                undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
                 $newentry->{form_id} = "patron_attr_$i";
                 push @{$items_by_class{$attr_type->class()}}, $newentry;
             }
@@ -926,6 +919,27 @@ sub patron_attributes_form {
 
 }
 
+sub add_guarantors {
+    my ( $patron, $input ) = @_;
+
+    my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
+    my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
+
+    for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
+        my $guarantor_id = $new_guarantor_id[$i];
+        my $relationship = $new_guarantor_relationship[$i];
+
+        next unless $guarantor_id;
+
+        $patron->add_guarantor(
+            {
+                guarantor_id => $guarantor_id,
+                relationship => $relationship,
+            }
+        );
+    }
+}
+
 # Local Variables:
 # tab-width: 8
 # End: