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