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