Bug 30952: Add spacing between itemtypes and subtype limits
[koha-ffzg.git] / suggestion / suggestion.pl
index c93aead..0e5ec8f 100755 (executable)
 use Modern::Perl;
 require Exporter;
 use CGI qw ( -utf8 );
-use C4::Auth;    # get_template_and_user
-use C4::Output;
+use C4::Auth qw( get_template_and_user );
+use C4::Output qw( output_html_with_http_headers );
 use C4::Suggestions;
-use C4::Koha;
-use C4::Budgets;
-use C4::Search;
+use C4::Koha qw( GetAuthorisedValues );
+use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget );
+use C4::Search qw( FindDuplicate GetDistinctValues );
 use C4::Members;
-use C4::Debug;
 use Koha::DateUtils qw( dt_from_string );
 use Koha::AuthorisedValues;
 use Koha::Acquisition::Currencies;
 use Koha::Libraries;
 use Koha::Patrons;
 
-use URI::Escape;
+use URI::Escape qw( uri_escape );
 
 sub Init{
     my $suggestion= shift @_;
     # "Managed by" is used only when a suggestion is being edited (not when created)
-    if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
+    if ($suggestion->{'suggesteddate'} eq "") {
         # new suggestion
         $suggestion->{suggesteddate} = dt_from_string;
         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
@@ -61,8 +60,9 @@ sub GetCriteriumDesc{
         }
         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
     }
-    return Koha::Libraries->find($criteriumvalue)->branchname
-        if $displayby =~ /branchcode/;
+    if ( $displayby =~ /branchcode/ ) {
+        return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
+    }
     if ( $displayby =~ /itemtype/ ) {
         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
         return $av->count ? $av->next->lib : 'Unknown';
@@ -91,11 +91,13 @@ my $managedby       = $input->param('managedby');
 my $displayby       = $input->param('displayby') || '';
 my $tabcode         = $input->param('tabcode');
 my $save_confirmed  = $input->param('save_confirmed') || 0;
+my $notify          = $input->param('notify');
+my $filter_archived = $input->param('filter_archived') || 0;
 
 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
 
 # filter informations which are not suggestion related.
-my $suggestion_ref  = $input->Vars;
+my $suggestion_ref  = { %{$input->Vars} }; # Copying, otherwise $input will be modified
 
 # get only the columns of Suggestion
 my $schema = Koha::Database->new()->schema;
@@ -103,10 +105,16 @@ my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
 
-delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field );
+delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode notify filter_archived );
 foreach (keys %$suggestion_ref){
     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
 }
+delete $suggestion_only->{branchcode} if $suggestion_only->{branchcode} eq '__ANY__';
+delete $suggestion_only->{budgetid}   if $suggestion_only->{budgetid}   eq '__ANY__';
+while ( my ( $k, $v ) = each %$suggestion_only ) {
+    delete $suggestion_only->{$k} if $v eq '';
+}
+
 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
         {
             template_name   => "suggestion/suggestion.tt",
@@ -130,20 +138,34 @@ if ( $op =~ /save/i ) {
             title => $suggestion_only->{title},
             author => $suggestion_only->{author},
             itemtype => $suggestion_only->{itemtype},
+            isbn => $suggestion_only->{isbn},
     });
 
-    if ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
+    my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
+    if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
+        push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
+        $template->param(
+            messages => \@messages,
+        );
+        delete $suggestion_ref->{suggesteddate};
+        delete $suggestion_ref->{manageddate};
+        delete $suggestion_ref->{managedby};
+        Init($suggestion_ref);
+    }
+    elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
         $template->param(
             messages => \@messages,
             need_confirm => 1
         );
         delete $suggestion_ref->{suggesteddate};
+        delete $suggestion_ref->{manageddate};
         Init($suggestion_ref);
     }
     else {
 
         for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
+            # FIXME Do we need this?
             $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
                 if $suggestion_only->{$date_key};
         }
@@ -163,16 +185,48 @@ if ( $op =~ /save/i ) {
         }
 
         if ( $suggestion_only->{'suggestionid'} > 0 ) {
+
+            $suggestion_only->{lastmodificationdate} = dt_from_string;
+            $suggestion_only->{lastmodificationby}   = C4::Context->userenv->{number};
+            $suggestion_only->{branchcode} = undef
+              if exists $suggestion_only->{branchcode}
+              && $suggestion_only->{branchcode} eq "";
+
             &ModSuggestion($suggestion_only);
+
+            if ( $notify ) {
+                my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
+                my $email_address = $patron->notice_email_address;
+                if ($patron->notice_email_address) {
+
+                    my $letter = C4::Letters::GetPreparedLetter(
+                        module      => 'suggestions',
+                        letter_code => 'NOTIFY_MANAGER',
+                        branchcode  => $patron->branchcode,
+                        lang        => $patron->lang,
+                        tables      => {
+                            suggestions => $suggestion_only->{suggestionid},
+                            branches    => $patron->branchcode,
+                            borrowers   => $patron->borrowernumber,
+                        },
+                    );
+                    C4::Letters::EnqueueLetter(
+                        {
+                            letter                 => $letter,
+                            borrowernumber         => $patron->borrowernumber,
+                            message_transport_type => 'email'
+                        }
+                    );
+                }
+            }
         } else {
             ###FIXME:Search here if suggestion already exists.
-            my $suggestions_loop =
-                SearchSuggestion( $suggestion_only );
-            if (@$suggestions_loop>=1){
+            my $suggestions= Koha::Suggestions->search_limited( $suggestion_only );
+            if ( $suggestions->count ) {
                 #some suggestion are answering the request Donot Add
                 my @messages;
-                for my $suggestion ( @$suggestions_loop ) {
-                    push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
+                while ( my $suggestion = $suggestions->next ) {
+                    push @messages, { type => 'error', code => 'already_exists', id => $suggestion->suggestionid };
                 }
                 $template->param( messages => \@messages );
             }
@@ -182,7 +236,7 @@ if ( $op =~ /save/i ) {
             }
             # empty fields, to avoid filter in "SearchSuggestion"
         }
-        map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
+        map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
         $op = 'else';
 
         if( $redirect eq 'purchase_suggestions' ) {
@@ -253,6 +307,16 @@ elsif ($op eq "update_status" ) {
     }
     redirect_with_params($input);
 }
+elsif ($op eq "archive" ) {
+    Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
+
+    redirect_with_params($input);
+}
+elsif ($op eq "unarchive" ) {
+    Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
+
+    redirect_with_params($input);
+}
 elsif ( $op eq 'update_itemtype' ) {
     my $new_itemtype = $input->param('suggestion_itemtype');
     foreach my $suggestionid (@editsuggestions) {
@@ -261,6 +325,14 @@ elsif ( $op eq 'update_itemtype' ) {
     }
     redirect_with_params($input);
 }
+elsif ( $op eq 'update_manager' ) {
+    my $managedby = $input->param('suggestion_managedby');
+    foreach my $suggestionid (@editsuggestions) {
+        next unless $suggestionid;
+        &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
+    }
+    redirect_with_params($input);
+}
 elsif ( $op eq 'show' ) {
     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
     my $budget = GetBudget $$suggestion_ref{budgetid};
@@ -269,7 +341,7 @@ elsif ( $op eq 'show' ) {
 }
 if ($op=~/else/) {
     $op='else';
-    
+
     $displayby||="STATUS";
     # distinct values of display by
     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
@@ -291,32 +363,66 @@ if ($op=~/else/) {
     {
         @criteria_dv = ( C4::Context->userenv->{'branch'} );
     }
+    # Pending tab first
+    if ( $displayby eq 'STATUS' ) {
+        @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv;
+        unshift @criteria_dv, 'ASKED';
+    }
+
+    unless ( exists $suggestion_ref->{branchcode} ) {
+        $suggestion_ref->{branchcode} = C4::Context->userenv->{'branch'};
+    }
 
     my @allsuggestions;
     foreach my $criteriumvalue ( @criteria_dv ) {
+        my $search_params = {%$suggestion_ref};
         # By default, display suggestions from current working branch
-        unless ( exists $$suggestion_ref{'branchcode'} ) {
-            $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
-        }
         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
 
-        next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' or $branchfilter ne '__ANY__' );
-        $$suggestion_ref{$displayby} = $criteriumvalue;
+        next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
+
+        $search_params->{$displayby} = $criteriumvalue;
+
+        # filter on date fields
+        foreach my $field (qw( suggesteddate manageddate accepteddate )) {
+            my $from    = delete $search_params->{"${field}_from"};
+            my $to      = delete $search_params->{"${field}_to"};
 
-        my $suggestions = &SearchSuggestion($suggestion_ref);
-        foreach my $suggestion (@$suggestions) {
-            if ($suggestion->{budgetid}){
-                my $bud = GetBudget( $suggestion->{budgetid} );
-                $suggestion->{budget_name} = $bud->{budget_name} if $bud;
+            my $from_dt = $from && eval { dt_from_string($from) };
+            my $to_dt   = $to && eval { dt_from_string($to) };
+
+            if ( $from_dt || $to_dt ) {
+                my $dtf = Koha::Database->new->schema->storage->datetime_parser;
+                if ( $from_dt && $to_dt ) {
+                    $search_params->{$field} = { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] };
+                } elsif ( $from_dt ) {
+                    $search_params->{$field} = { '>=' => $dtf->format_date($from_dt) };
+                } elsif ( $to_dt ) {
+                    $search_params->{$field} = { '<=' => $dtf->format_date($to_dt) };
+                }
             }
         }
-        push @allsuggestions,{
-                            "suggestiontype"=>$criteriumvalue||"suggest",
-                            "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
-                            "suggestionscount"=>scalar(@$suggestions),             
-                            'suggestions_loop'=>$suggestions,
-                            'reasonsloop'     => $reasonsloop,
-                            };
+        if ( $search_params->{budgetid} && $search_params->{budgetid} eq '__NONE__' ) {
+            $search_params->{budgetid} = [undef, '' ];
+        }
+        for my $f (qw (branchcode budgetid)) {
+            delete $search_params->{$f}
+              if $search_params->{$f} eq '__ANY__'
+              || $search_params->{$f} eq '';
+        }
+
+        my @suggestions =
+          Koha::Suggestions->search_limited(
+            { %$search_params, archived => $filter_archived } )->as_list;
+
+        push @allsuggestions,
+          {
+            "suggestiontype"      => $criteriumvalue || "suggest",
+            "suggestiontypelabel" => GetCriteriumDesc( $criteriumvalue, $displayby ) || "",
+            'suggestions'         => \@suggestions,
+            'reasonsloop'         => $reasonsloop,
+          }
+          if scalar @suggestions > 0;
 
         delete $$suggestion_ref{$displayby} unless $definedvalue;
     }
@@ -330,10 +436,11 @@ if ($op=~/else/) {
 
 $template->param(
     "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
-  for qw(managedby suggestedby acceptedby);
+  for qw(managedby suggestedby acceptedby lastmodificationby);
 
 $template->param(
     %$suggestion_ref,
+    filter_archived => $filter_archived,
     "op"             =>$op,
 );
 
@@ -351,7 +458,7 @@ $template->param( returnsuggestedby => $returnsuggestedby );
 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
 $template->param(patron_reason_loop=>$patron_reason_loop);
 
-#Budgets management
+# Budgets for filtering
 my $budgets = GetBudgets;
 my @budgets_loop;
 foreach my $budget ( @{$budgets} ) {
@@ -364,8 +471,25 @@ foreach my $budget ( @{$budgets} ) {
 
     push @budgets_loop, $budget;
 }
-
 $template->param( budgetsloop => \@budgets_loop);
+
+# Budgets for suggestion add or edition
+my $sugg_budget_loop = [];
+my $sugg_budgets     = GetBudgetHierarchy();
+foreach my $r ( @{$sugg_budgets} ) {
+    next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
+    my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
+    push @{$sugg_budget_loop},
+      {
+        b_id     => $r->{budget_id},
+        b_txt    => $r->{budget_name},
+        b_active => $r->{budget_period_active},
+        selected => $selected,
+      };
+}
+@{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
+$template->param( sugg_budgets => $sugg_budget_loop);
+
 if( $suggestion_ref->{STATUS} ) {
     $template->param(
         "statusselected_".$suggestion_ref->{STATUS} => 1,
@@ -373,9 +497,9 @@ if( $suggestion_ref->{STATUS} ) {
     );
 }
 
-my @currencies = Koha::Acquisition::Currencies->search;
+my $currencies = Koha::Acquisition::Currencies->search;
 $template->param(
-    currencies   => \@currencies,
+    currencies   => $currencies,
     suggestion   => $suggestion_ref,
     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
@@ -412,7 +536,7 @@ sub redirect_with_params {
         displayby branchcode title author isbn publishercode copyrightdate
         collectiontitle suggestedby suggesteddate_from suggesteddate_to
         manageddate_from manageddate_to accepteddate_from
-        accepteddate_to budgetid
+        accepteddate_to budgetid filter_archived
         )
       )
     {