ffzg/recall_notices.pl: added --interval and --dedup
[koha.git] / suggestion / suggestion.pl
index 72f40d3..845ed0e 100755 (executable)
@@ -4,33 +4,37 @@
 # Copyright 2006-2010 BibLibre
 
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
-use strict;
-#use warnings; FIXME - Bug 2505
+use Modern::Perl;
 require Exporter;
-use CGI;
+use CGI qw ( -utf8 );
 use C4::Auth;    # get_template_and_user
 use C4::Output;
 use C4::Suggestions;
-use C4::Koha; #GetItemTypes
-use C4::Branch;
+use C4::Koha;
 use C4::Budgets;
 use C4::Search;
-use C4::Dates qw(format_date);
 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;
 
 sub Init{
@@ -38,21 +42,13 @@ sub Init{
     # "Managed by" is used only when a suggestion is being edited (not when created)
     if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
         # new suggestion
-        $suggestion->{'suggesteddate'} = C4::Dates->today;
+        $suggestion->{suggesteddate} = dt_from_string;
         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
     }
     else {
         # editing of an existing suggestion
-        $suggestion->{'manageddate'} = C4::Dates->today;
+        $suggestion->{manageddate} = dt_from_string;
         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
-        # suggesteddate, when coming from the DB, needs to be formated
-        $suggestion->{'suggesteddate'} = format_date($suggestion->{'suggesteddate'});
-    }
-    foreach my $date ( qw(rejecteddate accepteddate) ){
-    $suggestion->{$date}=(($suggestion->{$date} eq "0000-00-00" ||$suggestion->{$date} eq "")?
-                                "":
-                                format_date($suggestion->{$date}) 
-                              );
     }
     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
 }
@@ -60,18 +56,22 @@ sub Init{
 sub GetCriteriumDesc{
     my ($criteriumvalue,$displayby)=@_;
     if ($displayby =~ /status/i) {
-        if ( grep { /^($criteriumvalue)$/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
-            return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue)));
-        } else {
-            return GetAuthorisedValueByCode('SUGGEST_STATUS', $criteriumvalue) || $criteriumvalue;
+        unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
+            my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
+            return $av->count ? $av->next->lib : 'Unknown';
         }
+        return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
+    }
+    return Koha::Libraries->find($criteriumvalue)->branchname
+        if $displayby =~ /branchcode/;
+    if ( $displayby =~ /itemtype/ ) {
+        my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
+        return $av->count ? $av->next->lib : 'Unknown';
     }
-    return (GetBranchName($criteriumvalue)) if ($displayby =~/branchcode/);
-    return (GetSupportName($criteriumvalue)) if ($displayby =~/itemtype/);
     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
-        my $borr=C4::Members::GetMember(borrowernumber=>$criteriumvalue);
-        return "" unless $borr;
-        return $$borr{surname} . ", " . $$borr{firstname};
+        my $patron = Koha::Patrons->find( $criteriumvalue );
+        return "" unless $patron;
+        return $patron->surname . ", " . $patron->firstname;
     }
     if ( $displayby =~ /budgetid/) {
         my $budget = GetBudget($criteriumvalue);
@@ -84,13 +84,14 @@ my $input           = CGI->new;
 my $redirect  = $input->param('redirect');
 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
 my $op              = $input->param('op')||'else';
-my @editsuggestions = $input->param('edit_field');
+my @editsuggestions = $input->multi_param('edit_field');
 my $suggestedby     = $input->param('suggestedby');
 my $returnsuggestedby = $input->param('returnsuggestedby');
 my $returnsuggested = $input->param('returnsuggested');
 my $managedby       = $input->param('managedby');
 my $displayby       = $input->param('displayby') || '';
 my $tabcode         = $input->param('tabcode');
+my $reasonsloop     = GetAuthorisedValues("SUGGEST");
 
 # filter informations which are not suggestion related.
 my $suggestion_ref  = $input->Vars;
@@ -98,7 +99,7 @@ my $suggestion_ref  = $input->Vars;
 # get only the columns of Suggestion
 my $schema = Koha::Database->new()->schema;
 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
-my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys($suggestion_ref) };
+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 );
@@ -110,7 +111,7 @@ my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
             template_name   => "suggestion/suggestion.tt",
             query           => $input,
             type            => "intranet",
-            flagsrequired   => { catalogue => 1 },
+            flagsrequired   => { acquisition => 'suggestions_manage' },
         }
     );
 
@@ -121,14 +122,23 @@ $template->param('borrowernumber' => $borrowernumber);
 ##  Operations
 ##
 if ( $op =~ /save/i ) {
-        if ( $suggestion_only->{"STATUS"} ) {
+    $suggestion_only->{suggesteddate} = dt_from_string( $suggestion_only->{suggesteddate} )
+        if $suggestion_only->{suggesteddate};
+
+    if ( $suggestion_only->{"STATUS"} ) {
         if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
-            $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = C4::Dates->today;
+            $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
         }
-        $suggestion_only->{"manageddate"} = C4::Dates->today;
+        $suggestion_only->{manageddate} = dt_from_string;
         $suggestion_only->{"managedby"}   = C4::Context->userenv->{number};
     }
+
+    my $otherreason = $input->param('other_reason');
+    if ($suggestion_only->{reason} eq 'other' && $otherreason) {
+        $suggestion_only->{reason} = $otherreason;
+    }
+
     if ( $suggestion_only->{'suggestionid'} > 0 ) {
         &ModSuggestion($suggestion_only);
     } else {
@@ -137,6 +147,11 @@ if ( $op =~ /save/i ) {
             SearchSuggestion( $suggestion_only );
         if (@$suggestions_loop>=1){
             #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} };
+            }
+            $template->param( messages => \@messages );
         } 
         else {    
             ## Adding some informations related to suggestion
@@ -160,33 +175,39 @@ elsif ($op=~/add/) {
 elsif ($op=~/edit/) {
     #Edit suggestion  
     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
+    $suggestion_ref->{reasonsloop} = $reasonsloop;
+    my $other_reason = 1;
+    foreach my $reason ( @{ $reasonsloop } ) {
+        if ($suggestion_ref->{reason} eq $reason->{lib}) {
+            $other_reason = 0;
+        }
+    }
+    $other_reason = 0 unless $suggestion_ref->{reason};
+    $template->param(other_reason => $other_reason);
     Init($suggestion_ref);
     $op ='save';
 }  
 elsif ($op eq "change" ) {
     # set accepted/rejected/managed informations if applicable
-    # ie= if the librarian has choosen some action on the suggestions
+    # ie= if the librarian has chosen some action on the suggestions
     if ($suggestion_only->{"STATUS"} eq "ACCEPTED"){
-        $suggestion_only->{"accepteddate"}=C4::Dates->today;
+        $suggestion_only->{accepteddate} = dt_from_string;
         $suggestion_only->{"acceptedby"}=C4::Context->userenv->{number};
     } elsif ($suggestion_only->{"STATUS"} eq "REJECTED"){
-        $suggestion_only->{"rejecteddate"}=C4::Dates->today;
+        $suggestion_only->{rejecteddate} = dt_from_string;
         $suggestion_only->{"rejectedby"}=C4::Context->userenv->{number};
     }
     if ($suggestion_only->{"STATUS"}){
-        $suggestion_only->{"manageddate"}=C4::Dates->today;
+        $suggestion_only->{manageddate} = dt_from_string;
         $suggestion_only->{"managedby"}=C4::Context->userenv->{number};
     }
     if ( my $reason = $$suggestion_ref{"reason$tabcode"}){
         if ( $reason eq "other" ) {
-                $reason = $$suggestion_ref{"other_reason$tabcode"};
+            $reason = $$suggestion_ref{"other_reason$tabcode"};
         }
-        $$suggestion_ref{'reason'}=$reason;
-    }
-    delete $$suggestion_ref{$_} foreach ("reason$tabcode", "other_reason$tabcode");
-     foreach (keys %$suggestion_ref){
-        delete $$suggestion_ref{$_} unless ($$suggestion_ref{$_});
+        $suggestion_only->{reason}=$reason;
     }
+
     foreach my $suggestionid (@editsuggestions) {
         next unless $suggestionid;
         $suggestion_only->{'suggestionid'}=$suggestionid;
@@ -214,7 +235,6 @@ elsif ($op eq "change" ) {
 }
 elsif ( $op eq 'show' ) {
     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
-    $$suggestion_ref{branchname} = GetBranchName $$suggestion_ref{branchcode};
     my $budget = GetBudget $$suggestion_ref{budgetid};
     $$suggestion_ref{budgetname} = $$budget{budget_name};
     Init($suggestion_ref);
@@ -234,11 +254,10 @@ if ($op=~/else/) {
             $criteria_has_empty = 1;
         }
     }
-    # agregate null and empty values under empty value
+    # aggregate null and empty values under empty value
     push @criteria_dv, '' if $criteria_has_empty;
 
     my @allsuggestions;
-    my $reasonsloop = GetAuthorisedValues("SUGGEST");
     foreach my $criteriumvalue ( @criteria_dv ) {
         # By default, display suggestions from current working branch
         unless ( exists $$suggestion_ref{'branchcode'} ) {
@@ -255,13 +274,6 @@ if ($op=~/else/) {
                 my $bud = GetBudget( $suggestion->{budgetid} );
                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
             }
-            foreach my $date (qw(suggesteddate manageddate accepteddate)) {
-                if ($suggestion->{$date} and $suggestion->{$date} ne "0000-00-00") {
-                    $suggestion->{$date} = format_date( $suggestion->{$date} );
-                } else {
-                    $suggestion->{$date} = "";
-                }
-            }
         }
         push @allsuggestions,{
                             "suggestiontype"=>$criteriumvalue||"suggest",
@@ -284,14 +296,16 @@ if ($op=~/else/) {
 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
 #    $debug || warn $$suggestion_ref{$element};
     if ($$suggestion_ref{$element}){
-        my $member=GetMember(borrowernumber=>$$suggestion_ref{$element});
+        my $patron = Koha::Patrons->find( $$suggestion_ref{$element} );
+        my $category = $patron->category;
         $template->param(
-            $element."_borrowernumber"=>$$member{borrowernumber},
-            $element."_firstname"=>$$member{firstname},
-            $element."_surname"=>$$member{surname},
-            $element."_branchcode"=>$$member{branchcode},
-            $element."_description"=>$$member{description},
-            $element."_category_type"=>$$member{category_type}
+            $element."_borrowernumber"=>$patron->borrowernumber,
+            $element."_firstname"=>$patron->firstname,
+            $element."_surname"=>$patron->surname,
+            $element."_cardnumber"=>$patron->cardnumber,
+            $element."_branchcode"=>$patron->branchcode,
+            $element."_description"=>$category->description,
+            $element."_category_type"=>$category->category_type,
         );
     }
 }
@@ -306,49 +320,15 @@ if(defined($returnsuggested) and $returnsuggested ne "noone")
     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
 }
 
-####################
-## Initializing selection lists
-
-#branch display management
-my $branchfilter = ($displayby ne "branchcode") ? $input->param('branchcode') : '';
-my $onlymine =
-     C4::Context->preference('IndependentBranches')
-  && C4::Context->userenv
-  && !C4::Context->IsSuperLibrarian()
-  && C4::Context->userenv->{branch};
-my $branches = GetBranches($onlymine);
-my @branchloop;
-
-foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
-    my %row = (
-        value      => $thisbranch,
-        branchname => $branches->{$thisbranch}->{'branchname'},
-        selected   => ($branchfilter and $branches->{$thisbranch}->{'branchcode'} eq $branchfilter ) || ( $$suggestion_ref{'branchcode'} and $branches->{$thisbranch}->{'branchcode'} eq $$suggestion_ref{'branchcode'} )
-    );
-    push @branchloop, \%row;
-}
-$branchfilter=C4::Context->userenv->{'branch'} if ($onlymine && !$branchfilter);
-
-$template->param( branchloop => \@branchloop,
-                branchfilter => $branchfilter);
+my $branchfilter = ($displayby ne "branchcode") ? $input->param('branchcode') : C4::Context->userenv->{'branch'};
 
-# the index parameter is different for item-level itemtypes
-my $supportlist = GetSupportList();
+$template->param(
+    branchfilter => $branchfilter,
+);
 
-foreach my $support (@$supportlist) {
-    $$support{'selected'} = (defined $$suggestion_ref{'itemtype'})
-        ? $$support{'itemtype'} eq $$suggestion_ref{'itemtype'}
-        : 0;
-    if ( $$support{'imageurl'} ) {
-        $$support{'imageurl'} = getitemtypeimagelocation( 'intranet', $$support{'imageurl'} );
-    } else {
-        delete $$support{'imageurl'};
-    }
-}
-$template->param(itemtypeloop=>$supportlist);
 $template->param( returnsuggestedby => $returnsuggestedby );
 
-my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG",$$suggestion_ref{'patronreason'});
+my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
 $template->param(patron_reason_loop=>$patron_reason_loop);
 
 #Budgets management
@@ -373,30 +353,17 @@ foreach my $budget ( @{$budgets} ) {
 }
 
 $template->param( budgetsloop => \@budgets_loop);
-$template->param( "statusselected_$$suggestion_ref{'STATUS'}" =>1) if ($$suggestion_ref{'STATUS'});
-
-# get currencies and rates
-my @rates = GetCurrencies();
-my $count = scalar @rates;
-my $active_currency = GetCurrency();
-my $selected_currency;
-if ($$suggestion_ref{'currency'}) {
-    $selected_currency = $$suggestion_ref{'currency'};
-}
-else {
-    $selected_currency = $active_currency->{currency};
+if( $suggestion_ref->{STATUS} ) {
+    $template->param(
+        "statusselected_".$suggestion_ref->{STATUS} => 1,
+        selected_status => $suggestion_ref->{STATUS}, # We need template var selected_status in the second part of the template where template var suggestion.STATUS is out of scope
+    );
 }
 
-my @loop_currency = ();
-for ( my $i = 0 ; $i < $count ; $i++ ) {
-    my %line;
-    $line{currcode} = $rates[$i]->{'currency'};
-    $line{rate}     = $rates[$i]->{'rate'};
-    $line{selected} = 1 if ($line{'currcode'} eq $selected_currency);
-    push @loop_currency, \%line;
-}
+my @currencies = Koha::Acquisition::Currencies->search;
 $template->param(
-    loop_currency => \@loop_currency,
+    currencies   => \@currencies,
+    suggestion   => $suggestion_ref,
     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
 );