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