Bug 4068: ensure accepting a suggestion does not hide the 'pending' tab
[koha.git] / suggestion / suggestion.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 # Copyright 2006-2010 BibLibre
5
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 require Exporter;
23 use CGI;
24 use C4::Auth;    # get_template_and_user
25 use C4::Output;
26 use C4::Suggestions;
27 use C4::Koha; #GetItemTypes
28 use C4::Branch;
29 use C4::Budgets;
30 use C4::Search;
31 use C4::Dates qw(format_date);
32 use C4::Members;
33 use C4::Debug;
34
35 sub Init{
36     my $suggestion= shift @_;
37     # "Managed by" is used only when a suggestion is being edited (not when created)
38     if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
39         # new suggestion
40         $suggestion->{'suggesteddate'} = C4::Dates->today;
41         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
42     }
43     else {
44         # editing of an existing suggestion
45         $suggestion->{'manageddate'} = C4::Dates->today;
46         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
47         # suggesteddate, when coming from the DB, needs to be formated
48         $suggestion->{'suggesteddate'} = format_date($suggestion->{'suggesteddate'});
49     }
50     foreach my $date ( qw(rejecteddate accepteddate) ){
51     $suggestion->{$date}=(($suggestion->{$date} eq "0000-00-00" ||$suggestion->{$date} eq "")?
52                                 "":
53                                 format_date($suggestion->{$date}) 
54                               );
55     }
56     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
57 }
58
59 sub GetCriteriumDesc{
60     my ($criteriumvalue,$displayby)=@_;
61     unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED) ) {
62         return GetAuthorisedValueByCode('SUGGEST_STATUS', $criteriumvalue ) || "Unknown";
63     }
64     return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
65     return (GetBranchName($criteriumvalue)) if ($displayby =~/branchcode/);
66     return (GetSupportName($criteriumvalue)) if ($displayby =~/itemtype/);
67     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
68         my $borr=C4::Members::GetMember(borrowernumber=>$criteriumvalue);
69         return "" unless $borr;
70         return $$borr{surname} . ", " . $$borr{firstname};
71     }
72     if ( $displayby =~ /budgetid/) {
73         my $budget = GetBudget($criteriumvalue);
74         return "" unless $budget;
75         return $$budget{budget_name};
76     }
77 }
78
79 my $input           = CGI->new;
80 my $redirect  = $input->param('redirect');
81 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
82 my $op              = $input->param('op')||'else';
83 my @editsuggestions = $input->param('edit_field');
84 my $suggestedby     = $input->param('suggestedby');
85 my $returnsuggestedby = $input->param('returnsuggestedby');
86 my $returnsuggested = $input->param('returnsuggested');
87 my $managedby       = $input->param('managedby');
88 my $displayby       = $input->param('displayby') || '';
89 my $tabcode         = $input->param('tabcode');
90
91 # filter informations which are not suggestion related.
92 my $suggestion_ref  = $input->Vars;
93
94 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field );
95 foreach (keys %$suggestion_ref){
96     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' || $op eq 'change'));
97 }
98 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
99         {
100             template_name   => "suggestion/suggestion.tmpl",
101             query           => $input,
102             type            => "intranet",
103             flagsrequired   => { catalogue => 1 },
104         }
105     );
106
107 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
108 $template->param('borrowernumber' => $borrowernumber);
109
110 #########################################
111 ##  Operations
112 ##
113 if ( $op =~ /save/i ) {
114         if ( $$suggestion_ref{"STATUS"} ) {
115         if ( my $tmpstatus = lc( $$suggestion_ref{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
116             $$suggestion_ref{ lc( $$suggestion_ref{"STATUS"}) . "date" } = C4::Dates->today;
117             $$suggestion_ref{ lc( $$suggestion_ref{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
118         }
119         $$suggestion_ref{"manageddate"} = C4::Dates->today;
120         $$suggestion_ref{"managedby"}   = C4::Context->userenv->{number};
121     }
122     if ( $$suggestion_ref{'suggestionid'} > 0 ) {
123         &ModSuggestion($suggestion_ref);
124     } else {
125         ###FIXME:Search here if suggestion already exists.
126         my $suggestions_loop =
127             SearchSuggestion( $suggestion_ref );
128         if (@$suggestions_loop>=1){
129             #some suggestion are answering the request Donot Add
130         } 
131         else {    
132             ## Adding some informations related to suggestion
133             &NewSuggestion($suggestion_ref);
134         }
135         # empty fields, to avoid filter in "SearchSuggestion"
136     }  
137     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
138     $op = 'else';
139
140     if( $redirect eq 'purchase_suggestions' ) {
141         print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
142     }
143
144 }
145 elsif ($op=~/add/) {
146     #Adds suggestion  
147     Init($suggestion_ref);
148     $op ='save';
149
150 elsif ($op=~/edit/) {
151     #Edit suggestion  
152     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
153     Init($suggestion_ref);
154     $op ='save';
155 }  
156 elsif ($op eq "change" ) {
157     # set accepted/rejected/managed informations if applicable
158     # ie= if the librarian has choosen some action on the suggestions
159     if ($$suggestion_ref{"STATUS"} eq "ACCEPTED"){
160         $$suggestion_ref{"accepteddate"}=C4::Dates->today;
161         $$suggestion_ref{"acceptedby"}=C4::Context->userenv->{number};
162     } elsif ($$suggestion_ref{"STATUS"} eq "REJECTED"){
163         $$suggestion_ref{"rejecteddate"}=C4::Dates->today;
164         $$suggestion_ref{"rejectedby"}=C4::Context->userenv->{number};
165     }
166     if ($$suggestion_ref{"STATUS"}){
167         $$suggestion_ref{"manageddate"}=C4::Dates->today;
168         $$suggestion_ref{"managedby"}=C4::Context->userenv->{number};
169     }
170     if ( my $reason = $$suggestion_ref{"reason$tabcode"}){
171         if ( $reason eq "other" ) {
172                 $reason = $$suggestion_ref{"other_reason$tabcode"};
173         }
174         $$suggestion_ref{'reason'}=$reason;
175     }
176     delete $$suggestion_ref{$_} foreach ("reason$tabcode", "other_reason$tabcode");
177      foreach (keys %$suggestion_ref){
178         delete $$suggestion_ref{$_} unless ($$suggestion_ref{$_});
179     }
180     foreach my $suggestionid (@editsuggestions) {
181         next unless $suggestionid;
182         $$suggestion_ref{'suggestionid'}=$suggestionid;
183         &ModSuggestion($suggestion_ref);
184     }
185     my $params;
186     foreach my $key (
187         qw(
188         displayby branchcode title author isbn publishercode copyrightdate
189         collectiontitle suggestedby suggesteddate_from suggesteddate_to
190         manageddate_from manageddate_to accepteddate_from
191         accepteddate_to budgetid
192         )
193       )
194     {
195         $params .= $key . '=' . $input->param($key) . '&'
196           if $input->param($key);
197     }
198     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
199 }elsif ($op eq "delete" ) {
200     foreach my $delete_field (@editsuggestions) {
201         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
202     }
203     $op = 'else';
204 }
205 elsif ( $op eq 'show' ) {
206     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
207     $$suggestion_ref{branchname} = GetBranchName $$suggestion_ref{branchcode};
208     my $budget = GetBudget $$suggestion_ref{budgetid};
209     $$suggestion_ref{budgetname} = $$budget{budget_name};
210     Init($suggestion_ref);
211 }
212 if ($op=~/else/) {
213     $op='else';
214     
215     $displayby||="STATUS";
216     delete $$suggestion_ref{'branchcode'} if($displayby eq "branchcode");
217     # distinct values of display by
218     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
219     my (@criteria_dv, $criteria_has_empty);
220     foreach (@$criteria_list) {
221         if ($_->{value}) {
222             push @criteria_dv, $_->{value};
223         } else {
224             $criteria_has_empty = 1;
225         }
226     }
227     # agregate null and empty values under empty value
228     push @criteria_dv, '' if $criteria_has_empty;
229
230     my @allsuggestions;
231     my $reasonsloop = GetAuthorisedValues("SUGGEST");
232     foreach my $criteriumvalue ( @criteria_dv ) {
233         # By default, display suggestions from current working branch
234         unless ( exists $$suggestion_ref{'branchcode'} ) {
235             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
236         }
237         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
238
239         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue );
240         $$suggestion_ref{$displayby} = $criteriumvalue;
241
242         my $suggestions = &SearchSuggestion($suggestion_ref);
243         foreach my $suggestion (@$suggestions) {
244             if ($suggestion->{budgetid}){
245                 my $bud = GetBudget( $suggestion->{budgetid} );
246                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
247             }
248             foreach my $date (qw(suggesteddate manageddate accepteddate)) {
249                 if ($suggestion->{$date} and $suggestion->{$date} ne "0000-00-00") {
250                     $suggestion->{$date} = format_date( $suggestion->{$date} );
251                 } else {
252                     $suggestion->{$date} = "";
253                 }
254             }
255         }
256         push @allsuggestions,{
257                             "suggestiontype"=>$criteriumvalue||"suggest",
258                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
259                             "suggestionscount"=>scalar(@$suggestions),             
260                             'suggestions_loop'=>$suggestions,
261                             'reasonsloop'     => $reasonsloop,
262                             };
263
264         delete $$suggestion_ref{$displayby} unless $definedvalue;
265     }
266
267     $template->param(
268         "displayby"=> $displayby,
269         "notabs"=> $displayby eq "",
270         suggestions       => \@allsuggestions,
271     );
272 }
273
274 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
275 #    $debug || warn $$suggestion_ref{$element};
276     if ($$suggestion_ref{$element}){
277         my $member=GetMember(borrowernumber=>$$suggestion_ref{$element});
278         $template->param(
279             $element."_borrowernumber"=>$$member{borrowernumber},
280             $element."_firstname"=>$$member{firstname},
281             $element."_surname"=>$$member{surname},
282             $element."_branchcode"=>$$member{branchcode},
283             $element."_description"=>$$member{description},
284             $element."_category_type"=>$$member{category_type}
285         );
286     }
287 }
288 $template->param(
289     %$suggestion_ref,  
290     "op_$op"                => 1,
291     "op"             =>$op,
292 );
293
294 if(defined($returnsuggested) and $returnsuggested ne "noone")
295 {
296     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
297 }
298
299 ####################
300 ## Initializing selection lists
301
302 #branch display management
303 my $branchfilter = ($displayby ne "branchcode") ? $input->param('branchcode') : '';
304 my $onlymine =
305      C4::Context->preference('IndependentBranches')
306   && C4::Context->userenv
307   && !C4::Context->IsSuperLibrarian()
308   && C4::Context->userenv->{branch};
309 my $branches = GetBranches($onlymine);
310 my @branchloop;
311
312 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
313     my %row = (
314         value      => $thisbranch,
315         branchname => $branches->{$thisbranch}->{'branchname'},
316         selected   => ($branchfilter and $branches->{$thisbranch}->{'branchcode'} eq $branchfilter ) || ( $$suggestion_ref{'branchcode'} and $branches->{$thisbranch}->{'branchcode'} eq $$suggestion_ref{'branchcode'} )
317     );
318     push @branchloop, \%row;
319 }
320 $branchfilter=C4::Context->userenv->{'branch'} if ($onlymine && !$branchfilter);
321
322 $template->param( branchloop => \@branchloop,
323                 branchfilter => $branchfilter);
324
325 # the index parameter is different for item-level itemtypes
326 my $supportlist = GetSupportList();
327
328 foreach my $support (@$supportlist) {
329     $$support{'selected'} = (defined $$suggestion_ref{'itemtype'})
330         ? $$support{'itemtype'} eq $$suggestion_ref{'itemtype'}
331         : 0;
332     if ( $$support{'imageurl'} ) {
333         $$support{'imageurl'} = getitemtypeimagelocation( 'intranet', $$support{'imageurl'} );
334     } else {
335         delete $$support{'imageurl'};
336     }
337 }
338 $template->param(itemtypeloop=>$supportlist);
339 $template->param( returnsuggestedby => $returnsuggestedby );
340
341 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG",$$suggestion_ref{'patronreason'});
342 $template->param(patron_reason_loop=>$patron_reason_loop);
343
344 #Budgets management
345 my $budgets = [];
346 if ($branchfilter) {
347     my $searchbudgets = { budget_branchcode => $branchfilter };
348     $budgets = GetBudgets($searchbudgets);
349 } else {
350     $budgets = GetBudgets(undef);
351 }
352
353 my @budgets_loop;
354 foreach my $budget ( @{$budgets} ) {
355     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
356
357     ## Please see file perltidy.ERR
358     $budget->{'selected'} = 1
359         if ($$suggestion_ref{'budgetid'}
360         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
361
362     push @budgets_loop, $budget;
363 }
364
365 $template->param( budgetsloop => \@budgets_loop);
366 $template->param( "statusselected_$$suggestion_ref{'STATUS'}" =>1) if ($$suggestion_ref{'STATUS'});
367
368 # get currencies and rates
369 my @rates = GetCurrencies();
370 my $count = scalar @rates;
371 my $active_currency = GetCurrency();
372 my $selected_currency;
373 if ($$suggestion_ref{'currency'}) {
374     $selected_currency = $$suggestion_ref{'currency'};
375 }
376 else {
377     $selected_currency = $active_currency->{currency};
378 }
379
380 my @loop_currency = ();
381 for ( my $i = 0 ; $i < $count ; $i++ ) {
382     my %line;
383     $line{currcode} = $rates[$i]->{'currency'};
384     $line{rate}     = $rates[$i]->{'rate'};
385     $line{selected} = 1 if ($line{'currcode'} eq $selected_currency);
386     push @loop_currency, \%line;
387 }
388 $template->param(
389     loop_currency => \@loop_currency,
390     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
391     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
392 );
393
394 # lists of distinct values (without empty) for filters
395 my %hashlists;
396 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
397     my $values_list;
398     $values_list = GetDistinctValues( "suggestions." . $field );
399     my @codes_list = map {
400         {   'code' => $$_{'value'},
401             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
402             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
403         }
404     } grep {
405         $$_{'value'}
406     } @$values_list;
407     $hashlists{ lc($field) . "_loop" } = \@codes_list;
408 }
409
410 $template->param(
411     %hashlists,
412     borrowernumber           => $input->param('borrowernumber'),
413     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
414 );
415 output_html_with_http_headers $input, $cookie, $template->output;