Bug 25521: Remove cart_to_shelf note from NewItemsDefaultLocation syspref
[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   => { suggestions => 'suggestions_manage' },
115         }
116     );
117
118 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
119 $template->param('borrowernumber' => $borrowernumber);
120 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
121
122 #########################################
123 ##  Operations
124 ##
125 if ( $op =~ /save/i ) {
126
127     for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
128         $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
129             if $suggestion_only->{$date_key};
130     }
131
132     if ( $suggestion_only->{"STATUS"} ) {
133         if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
134             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
135             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
136         }
137         $suggestion_only->{manageddate} = dt_from_string;
138         $suggestion_only->{"managedby"}   = C4::Context->userenv->{number};
139     }
140
141     my $otherreason = $input->param('other_reason');
142     if ($suggestion_only->{reason} eq 'other' && $otherreason) {
143         $suggestion_only->{reason} = $otherreason;
144     }
145
146     if ( $suggestion_only->{'suggestionid'} > 0 ) {
147         &ModSuggestion($suggestion_only);
148     } else {
149         ###FIXME:Search here if suggestion already exists.
150         my $suggestions_loop =
151             SearchSuggestion( $suggestion_only );
152         if (@$suggestions_loop>=1){
153             #some suggestion are answering the request Donot Add
154             my @messages;
155             for my $suggestion ( @$suggestions_loop ) {
156                 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
157             }
158             $template->param( messages => \@messages );
159         } 
160         else {    
161             ## Adding some informations related to suggestion
162             &NewSuggestion($suggestion_only);
163         }
164         # empty fields, to avoid filter in "SearchSuggestion"
165     }  
166     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
167     $op = 'else';
168
169     if( $redirect eq 'purchase_suggestions' ) {
170         print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
171     }
172
173 }
174 elsif ($op=~/add/) {
175     #Adds suggestion  
176     Init($suggestion_ref);
177     $op ='save';
178
179 elsif ($op=~/edit/) {
180     #Edit suggestion  
181     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
182     $suggestion_ref->{reasonsloop} = $reasonsloop;
183     my $other_reason = 1;
184     foreach my $reason ( @{ $reasonsloop } ) {
185         if ($suggestion_ref->{reason} eq $reason->{lib}) {
186             $other_reason = 0;
187         }
188     }
189     $other_reason = 0 unless $suggestion_ref->{reason};
190     $template->param(other_reason => $other_reason);
191     Init($suggestion_ref);
192     $op ='save';
193 }  
194 elsif ($op eq "change" ) {
195
196     my $suggestion;
197     # set accepted/rejected/managed informations if applicable
198     # ie= if the librarian has chosen some action on the suggestions
199     my $STATUS      = $input->param('STATUS');
200     my $accepted_by = $input->param('acceptedby');
201     if ( $STATUS eq "ACCEPTED" ) {
202         $suggestion = {
203             accepteddate => dt_from_string,
204             acceptedby => C4::Context->userenv->{number},
205         };
206     }
207     elsif ( $STATUS eq "REJECTED" ) {
208         $suggestion = {
209             rejecteddate => dt_from_string,
210             rejectedby   => C4::Context->userenv->{number},
211         };
212     }
213     if ($STATUS) {
214         $suggestion->{manageddate} = dt_from_string;
215         $suggestion->{managedby}   = C4::Context->userenv->{number};
216         $suggestion->{STATUS}      = $STATUS;
217     }
218     if ( my $reason = $input->param("reason$tabcode") ) {
219         if ( $reason eq "other" ) {
220             $reason = $input->param("other_reason$tabcode");
221         }
222         $suggestion->{reason} = $reason;
223     }
224
225     foreach my $suggestionid (@editsuggestions) {
226         next unless $suggestionid;
227         $suggestion->{suggestionid} = $suggestionid;
228         &ModSuggestion($suggestion);
229     }
230     my $params = '';
231     foreach my $key (
232         qw(
233         displayby branchcode title author isbn publishercode copyrightdate
234         collectiontitle suggestedby suggesteddate_from suggesteddate_to
235         manageddate_from manageddate_to accepteddate_from
236         accepteddate_to budgetid
237         )
238       )
239     {
240         $params .= $key . '=' . uri_escape($input->param($key)) . '&'
241           if defined($input->param($key));
242     }
243     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
244 }elsif ($op eq "delete" ) {
245     foreach my $delete_field (@editsuggestions) {
246         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
247     }
248     $op = 'else';
249 }
250 elsif ( $op eq 'show' ) {
251     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
252     my $budget = GetBudget $$suggestion_ref{budgetid};
253     $$suggestion_ref{budgetname} = $$budget{budget_name};
254     Init($suggestion_ref);
255 }
256 if ($op=~/else/) {
257     $op='else';
258     
259     $displayby||="STATUS";
260     # distinct values of display by
261     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
262     my (@criteria_dv, $criteria_has_empty);
263     foreach (@$criteria_list) {
264         if ($_->{value}) {
265             push @criteria_dv, $_->{value};
266         } else {
267             $criteria_has_empty = 1;
268         }
269     }
270     # aggregate null and empty values under empty value
271     push @criteria_dv, '' if $criteria_has_empty;
272
273     # Hack to not modify GetDistinctValues for this specific case
274     if (   $displayby eq 'branchcode'
275         && C4::Context->preference('IndependentBranches')
276         && not C4::Context->IsSuperLibrarian )
277     {
278         @criteria_dv = ( C4::Context->userenv->{'branch'} );
279     }
280
281     my @allsuggestions;
282     foreach my $criteriumvalue ( @criteria_dv ) {
283         # By default, display suggestions from current working branch
284         unless ( exists $$suggestion_ref{'branchcode'} ) {
285             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
286         }
287         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
288
289         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' or $branchfilter ne '__ANY__' );
290         $$suggestion_ref{$displayby} = $criteriumvalue;
291
292         my $suggestions = &SearchSuggestion($suggestion_ref);
293         foreach my $suggestion (@$suggestions) {
294             if ($suggestion->{budgetid}){
295                 my $bud = GetBudget( $suggestion->{budgetid} );
296                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
297             }
298         }
299         push @allsuggestions,{
300                             "suggestiontype"=>$criteriumvalue||"suggest",
301                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
302                             "suggestionscount"=>scalar(@$suggestions),             
303                             'suggestions_loop'=>$suggestions,
304                             'reasonsloop'     => $reasonsloop,
305                             };
306
307         delete $$suggestion_ref{$displayby} unless $definedvalue;
308     }
309
310     $template->param(
311         "displayby"=> $displayby,
312         "notabs"=> $displayby eq "",
313         suggestions       => \@allsuggestions,
314     );
315 }
316
317 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
318 #    $debug || warn $$suggestion_ref{$element};
319     if ($$suggestion_ref{$element}){
320         my $patron = Koha::Patrons->find( $$suggestion_ref{$element} );
321         my $category = $patron->category;
322         $template->param(
323             $element."_borrowernumber"=>$patron->borrowernumber,
324             $element."_firstname"=>$patron->firstname,
325             $element."_surname"=>$patron->surname,
326             $element."_cardnumber"=>$patron->cardnumber,
327             $element."_branchcode"=>$patron->branchcode,
328             $element."_description"=>$category->description,
329             $element."_category_type"=>$category->category_type,
330         );
331     }
332 }
333 $template->param(
334     %$suggestion_ref,  
335     "op_$op"                => 1,
336     "op"             =>$op,
337 );
338
339 if(defined($returnsuggested) and $returnsuggested ne "noone")
340 {
341     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
342 }
343
344 $template->param(
345     branchfilter => $branchfilter,
346 );
347
348 $template->param( returnsuggestedby => $returnsuggestedby );
349
350 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
351 $template->param(patron_reason_loop=>$patron_reason_loop);
352
353 #Budgets management
354 my $budgets = GetBudgets;
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 if( $suggestion_ref->{STATUS} ) {
369     $template->param(
370         "statusselected_".$suggestion_ref->{STATUS} => 1,
371         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
372     );
373 }
374
375 my @currencies = Koha::Acquisition::Currencies->search;
376 $template->param(
377     currencies   => \@currencies,
378     suggestion   => $suggestion_ref,
379     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
380     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
381 );
382
383 # lists of distinct values (without empty) for filters
384 my %hashlists;
385 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
386     my $values_list;
387     $values_list = GetDistinctValues( "suggestions." . $field );
388     my @codes_list = map {
389         {   'code' => $$_{'value'},
390             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
391             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
392         }
393     } grep {
394         $$_{'value'}
395     } @$values_list;
396     $hashlists{ lc($field) . "_loop" } = \@codes_list;
397 }
398
399 $template->param(
400     %hashlists,
401     borrowernumber           => ($input->param('borrowernumber') // undef),
402     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
403 );
404 output_html_with_http_headers $input, $cookie, $template->output;