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