Bug 23590: Remove unused variable
[srvgit] / 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 use Koha::DateUtils qw( dt_from_string );
32 use Koha::AuthorisedValues;
33 use Koha::Acquisition::Currencies;
34 use Koha::Libraries;
35 use Koha::Patrons;
36
37 use URI::Escape;
38
39 sub Init{
40     my $suggestion= shift @_;
41     # "Managed by" is used only when a suggestion is being edited (not when created)
42     if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
43         # new suggestion
44         $suggestion->{suggesteddate} = dt_from_string;
45         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
46     }
47     else {
48         # editing of an existing suggestion
49         $suggestion->{manageddate} = dt_from_string;
50         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
51     }
52     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
53 }
54
55 sub GetCriteriumDesc{
56     my ($criteriumvalue,$displayby)=@_;
57     if ($displayby =~ /status/i) {
58         unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
59             my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
60             return $av->count ? $av->next->lib : 'Unknown';
61         }
62         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
63     }
64     return Koha::Libraries->find($criteriumvalue)->branchname
65         if $displayby =~ /branchcode/;
66     if ( $displayby =~ /itemtype/ ) {
67         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
68         return $av->count ? $av->next->lib : 'Unknown';
69     }
70     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
71         my $patron = Koha::Patrons->find( $criteriumvalue );
72         return "" unless $patron;
73         return $patron->surname . ", " . $patron->firstname;
74     }
75     if ( $displayby =~ /budgetid/) {
76         my $budget = GetBudget($criteriumvalue);
77         return "" unless $budget;
78         return $$budget{budget_name};
79     }
80 }
81
82 my $input           = CGI->new;
83 my $redirect  = $input->param('redirect');
84 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
85 my $op              = $input->param('op')||'else';
86 my @editsuggestions = $input->multi_param('suggestionid');
87 my $suggestedby     = $input->param('suggestedby');
88 my $returnsuggestedby = $input->param('returnsuggestedby');
89 my $returnsuggested = $input->param('returnsuggested');
90 my $managedby       = $input->param('managedby');
91 my $displayby       = $input->param('displayby') || '';
92 my $tabcode         = $input->param('tabcode');
93 my $save_confirmed  = $input->param('save_confirmed') || 0;
94 my $notify          = $input->param('notify');
95
96 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
97
98 # filter informations which are not suggestion related.
99 my $suggestion_ref  = $input->Vars;
100
101 # get only the columns of Suggestion
102 my $schema = Koha::Database->new()->schema;
103 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
104 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
105 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
106
107 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field notify );
108 foreach (keys %$suggestion_ref){
109     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
110 }
111 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
112         {
113             template_name   => "suggestion/suggestion.tt",
114             query           => $input,
115             type            => "intranet",
116             flagsrequired   => { suggestions => 'suggestions_manage' },
117         }
118     );
119
120 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
121 $template->param('borrowernumber' => $borrowernumber);
122 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
123
124 #########################################
125 ##  Operations
126 ##
127
128 if ( $op =~ /save/i ) {
129     my @messages;
130     my $biblio = MarcRecordFromNewSuggestion({
131             title => $suggestion_only->{title},
132             author => $suggestion_only->{author},
133             itemtype => $suggestion_only->{itemtype},
134     });
135
136     if ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
137         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
138         $template->param(
139             messages => \@messages,
140             need_confirm => 1
141         );
142         delete $suggestion_ref->{suggesteddate};
143         Init($suggestion_ref);
144     }
145     else {
146
147         for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
148             $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
149                 if $suggestion_only->{$date_key};
150         }
151
152         if ( $suggestion_only->{"STATUS"} ) {
153             if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
154                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
155                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
156             }
157             $suggestion_only->{manageddate} = dt_from_string;
158             $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
159         }
160
161         my $otherreason = $input->param('other_reason');
162         if ($suggestion_only->{reason} eq 'other' && $otherreason) {
163             $suggestion_only->{reason} = $otherreason;
164         }
165
166         if ( $suggestion_only->{'suggestionid'} > 0 ) {
167
168             $suggestion_only->{lastmodificationdate} = dt_from_string;
169             $suggestion_only->{lastmodificationby}   = C4::Context->userenv->{number};
170
171             &ModSuggestion($suggestion_only);
172
173             if ( $notify ) {
174                 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
175                 my $email_address = $patron->notice_email_address;
176                 if ($patron->notice_email_address) {
177                     my $library = $patron->library;
178                     my $admin_email_address = $library->branchemail
179                       || C4::Context->preference('KohaAdminEmailAddress');
180
181                     my $letter = C4::Letters::GetPreparedLetter(
182                         module      => 'suggestions',
183                         letter_code => 'TO_PROCESS',
184                         branchcode  => $patron->branchcode,
185                         lang        => $patron->lang,
186                         tables      => {
187                             suggestions => $suggestion_only->{suggestionid},
188                             branches    => $patron->branchcode,
189                             borrowers   => $patron->borrowernumber,
190                         },
191                     );
192                     C4::Letters::EnqueueLetter(
193                         {
194                             letter                 => $letter,
195                             borrowernumber         => $patron->borrowernumber,
196                             message_transport_type => 'email',
197                             from_address           => $admin_email_address,
198                         }
199                     );
200                 }
201             }
202         } else {
203             ###FIXME:Search here if suggestion already exists.
204             my $suggestions_loop =
205                 SearchSuggestion( $suggestion_only );
206             if (@$suggestions_loop>=1){
207                 #some suggestion are answering the request Donot Add
208                 my @messages;
209                 for my $suggestion ( @$suggestions_loop ) {
210                     push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
211                 }
212                 $template->param( messages => \@messages );
213             }
214             else {
215                 ## Adding some informations related to suggestion
216                 &NewSuggestion($suggestion_only);
217             }
218             # empty fields, to avoid filter in "SearchSuggestion"
219         }
220         map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
221         $op = 'else';
222
223         if( $redirect eq 'purchase_suggestions' ) {
224             print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
225         }
226     }
227 }
228 elsif ($op=~/add/) {
229     #Adds suggestion
230     Init($suggestion_ref);
231     $op ='save';
232 }
233 elsif ($op=~/edit/) {
234     #Edit suggestion  
235     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
236     $suggestion_ref->{reasonsloop} = $reasonsloop;
237     my $other_reason = 1;
238     foreach my $reason ( @{ $reasonsloop } ) {
239         if ($suggestion_ref->{reason} eq $reason->{lib}) {
240             $other_reason = 0;
241         }
242     }
243     $other_reason = 0 unless $suggestion_ref->{reason};
244     $template->param(other_reason => $other_reason);
245     Init($suggestion_ref);
246     $op ='save';
247 }  
248 elsif ($op eq "update_status" ) {
249
250     my $suggestion;
251     # set accepted/rejected/managed informations if applicable
252     # ie= if the librarian has chosen some action on the suggestions
253     my $STATUS      = $input->param('STATUS');
254     my $accepted_by = $input->param('acceptedby');
255     if ( $STATUS eq "ACCEPTED" ) {
256         $suggestion = {
257             accepteddate => dt_from_string,
258             acceptedby => C4::Context->userenv->{number},
259         };
260     }
261     elsif ( $STATUS eq "REJECTED" ) {
262         $suggestion = {
263             rejecteddate => dt_from_string,
264             rejectedby   => C4::Context->userenv->{number},
265         };
266     }
267     if ($STATUS) {
268         $suggestion->{manageddate} = dt_from_string;
269         $suggestion->{managedby}   = C4::Context->userenv->{number};
270         $suggestion->{STATUS}      = $STATUS;
271     }
272     if ( my $reason = $input->param("reason") ) {
273         if ( $reason eq "other" ) {
274             $reason = $input->param("other_reason");
275         }
276         $suggestion->{reason} = $reason;
277     }
278
279     foreach my $suggestionid (@editsuggestions) {
280         next unless $suggestionid;
281         $suggestion->{suggestionid} = $suggestionid;
282         &ModSuggestion($suggestion);
283     }
284     redirect_with_params($input);
285 }elsif ($op eq "delete" ) {
286     foreach my $delete_field (@editsuggestions) {
287         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
288     }
289     redirect_with_params($input);
290 }
291 elsif ( $op eq 'update_itemtype' ) {
292     my $new_itemtype = $input->param('suggestion_itemtype');
293     foreach my $suggestionid (@editsuggestions) {
294         next unless $suggestionid;
295         &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
296     }
297     redirect_with_params($input);
298 }
299 elsif ( $op eq 'update_manager' ) {
300     my $managedby = $input->param('suggestion_managedby');
301     foreach my $suggestionid (@editsuggestions) {
302         next unless $suggestionid;
303         &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
304     }
305     redirect_with_params($input);
306 }
307 elsif ( $op eq 'show' ) {
308     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
309     my $budget = GetBudget $$suggestion_ref{budgetid};
310     $$suggestion_ref{budgetname} = $$budget{budget_name};
311     Init($suggestion_ref);
312 }
313 if ($op=~/else/) {
314     $op='else';
315     
316     $displayby||="STATUS";
317     # distinct values of display by
318     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
319     my (@criteria_dv, $criteria_has_empty);
320     foreach (@$criteria_list) {
321         if ($_->{value}) {
322             push @criteria_dv, $_->{value};
323         } else {
324             $criteria_has_empty = 1;
325         }
326     }
327     # aggregate null and empty values under empty value
328     push @criteria_dv, '' if $criteria_has_empty;
329
330     # Hack to not modify GetDistinctValues for this specific case
331     if (   $displayby eq 'branchcode'
332         && C4::Context->preference('IndependentBranches')
333         && not C4::Context->IsSuperLibrarian )
334     {
335         @criteria_dv = ( C4::Context->userenv->{'branch'} );
336     }
337
338     my @allsuggestions;
339     foreach my $criteriumvalue ( @criteria_dv ) {
340         # By default, display suggestions from current working branch
341         unless ( exists $$suggestion_ref{'branchcode'} ) {
342             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
343         }
344         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
345
346         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' or $branchfilter ne '__ANY__' );
347         $$suggestion_ref{$displayby} = $criteriumvalue;
348
349         my $suggestions = &SearchSuggestion($suggestion_ref);
350         foreach my $suggestion (@$suggestions) {
351             if ($suggestion->{budgetid}){
352                 my $bud = GetBudget( $suggestion->{budgetid} );
353                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
354             }
355         }
356         push @allsuggestions,{
357                             "suggestiontype"=>$criteriumvalue||"suggest",
358                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
359                             "suggestionscount"=>scalar(@$suggestions),             
360                             'suggestions_loop'=>$suggestions,
361                             'reasonsloop'     => $reasonsloop,
362                             };
363
364         delete $$suggestion_ref{$displayby} unless $definedvalue;
365     }
366
367     $template->param(
368         "displayby"=> $displayby,
369         "notabs"=> $displayby eq "",
370         suggestions       => \@allsuggestions,
371     );
372 }
373
374 $template->param(
375     "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
376   for qw(managedby suggestedby acceptedby lastmodificationby);
377
378 $template->param(
379     %$suggestion_ref,
380     "op"             =>$op,
381 );
382
383 if(defined($returnsuggested) and $returnsuggested ne "noone")
384 {
385     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
386 }
387
388 $template->param(
389     branchfilter => $branchfilter,
390 );
391
392 $template->param( returnsuggestedby => $returnsuggestedby );
393
394 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
395 $template->param(patron_reason_loop=>$patron_reason_loop);
396
397 #Budgets management
398 my $budgets = GetBudgets;
399 my @budgets_loop;
400 foreach my $budget ( @{$budgets} ) {
401     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
402
403     ## Please see file perltidy.ERR
404     $budget->{'selected'} = 1
405         if ($$suggestion_ref{'budgetid'}
406         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
407
408     push @budgets_loop, $budget;
409 }
410
411 $template->param( budgetsloop => \@budgets_loop);
412 if( $suggestion_ref->{STATUS} ) {
413     $template->param(
414         "statusselected_".$suggestion_ref->{STATUS} => 1,
415         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
416     );
417 }
418
419 my @currencies = Koha::Acquisition::Currencies->search;
420 $template->param(
421     currencies   => \@currencies,
422     suggestion   => $suggestion_ref,
423     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
424     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
425 );
426
427 # lists of distinct values (without empty) for filters
428 my %hashlists;
429 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
430     my $values_list;
431     $values_list = GetDistinctValues( "suggestions." . $field );
432     my @codes_list = map {
433         {   'code' => $$_{'value'},
434             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
435             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
436         }
437     } grep {
438         $$_{'value'}
439     } @$values_list;
440     $hashlists{ lc($field) . "_loop" } = \@codes_list;
441 }
442
443 $template->param(
444     %hashlists,
445     borrowernumber           => ($input->param('borrowernumber') // undef),
446     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
447 );
448 output_html_with_http_headers $input, $cookie, $template->output;
449
450 sub redirect_with_params {
451     my ( $input ) = @_;
452     my $params = '';
453     foreach my $key (
454         qw(
455         displayby branchcode title author isbn publishercode copyrightdate
456         collectiontitle suggestedby suggesteddate_from suggesteddate_to
457         manageddate_from manageddate_to accepteddate_from
458         accepteddate_to budgetid
459         )
460       )
461     {
462         $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
463           if defined($input->param($key));
464     }
465     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
466 }