Bug 35181: Don't pass undef to header
[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 qw( get_template_and_user );
24 use C4::Output qw( output_html_with_http_headers output_and_exit_if_error );
25 use C4::Suggestions;
26 use C4::Koha qw( GetAuthorisedValues );
27 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget );
28 use C4::Search qw( FindDuplicate GetDistinctValues );
29 use C4::Members;
30 use Koha::DateUtils qw( dt_from_string );
31 use Koha::AuthorisedValues;
32 use Koha::Acquisition::Currencies;
33 use Koha::Libraries;
34 use Koha::Patrons;
35 use Koha::Suggestions;
36 use Koha::Token;
37
38 use URI::Escape qw( 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 "") {
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     if ( $displayby =~ /branchcode/ ) {
66         return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
67     }
68     if ( $displayby =~ /itemtype/ ) {
69         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
70         return $av->count ? $av->next->lib : 'Unknown';
71     }
72     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
73         my $patron = Koha::Patrons->find( $criteriumvalue );
74         return "" unless $patron;
75         return $patron->surname . ", " . $patron->firstname;
76     }
77     if ( $displayby =~ /budgetid/) {
78         my $budget = GetBudget($criteriumvalue);
79         return "" unless $budget;
80         return $$budget{budget_name};
81     }
82 }
83
84 my $input           = CGI->new;
85 my $redirect  = $input->param('redirect');
86 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
87 my $op              = $input->param('op')||'else';
88 my @editsuggestions = $input->multi_param('suggestionid');
89 my $suggestedby     = $input->param('suggestedby');
90 my $returnsuggestedby = $input->param('returnsuggestedby');
91 my $returnsuggested = $input->param('returnsuggested');
92 my $managedby       = $input->param('managedby');
93 my $displayby       = $input->param('displayby') || '';
94 my $tabcode         = $input->param('tabcode');
95 my $save_confirmed  = $input->param('save_confirmed') || 0;
96 my $notify          = $input->param('notify');
97 my $filter_archived = $input->param('filter_archived') || 0;
98
99 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
100
101 # filter informations which are not suggestion related.
102 my $suggestion_ref  = { %{$input->Vars} }; # Copying, otherwise $input will be modified
103 delete $suggestion_ref->{csrf_token};
104
105 # get only the columns of Suggestion
106 my $schema = Koha::Database->new()->schema;
107 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
108 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
109 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
110
111 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode notify filter_archived );
112 foreach (keys %$suggestion_ref){
113     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
114 }
115 delete $suggestion_only->{branchcode} if $suggestion_only->{branchcode} eq '__ANY__';
116 delete $suggestion_only->{budgetid}   if $suggestion_only->{budgetid}   eq '__ANY__';
117 while ( my ( $k, $v ) = each %$suggestion_only ) {
118     delete $suggestion_only->{$k} if $v eq '';
119 }
120
121 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
122         {
123             template_name   => "suggestion/suggestion.tt",
124             query           => $input,
125             type            => "intranet",
126             flagsrequired   => { suggestions => 'suggestions_manage' },
127         }
128     );
129
130 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
131 $template->param('borrowernumber' => $borrowernumber);
132 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
133
134 #########################################
135 ##  Operations
136 ##
137
138 if ( $op =~ /save/i ) {
139     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
140     my @messages;
141     my $biblio = MarcRecordFromNewSuggestion({
142             title => $suggestion_only->{title},
143             author => $suggestion_only->{author},
144             itemtype => $suggestion_only->{itemtype},
145             isbn => $suggestion_only->{isbn},
146     });
147
148     my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
149     if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
150         push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
151         $template->param(
152             messages => \@messages,
153         );
154         delete $suggestion_ref->{suggesteddate};
155         delete $suggestion_ref->{manageddate};
156         delete $suggestion_ref->{managedby};
157         Init($suggestion_ref);
158     }
159     elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
160         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
161         $template->param(
162             messages => \@messages,
163             need_confirm => 1
164         );
165         delete $suggestion_ref->{suggesteddate};
166         delete $suggestion_ref->{manageddate};
167         Init($suggestion_ref);
168     }
169     else {
170
171         for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
172             # FIXME Do we need this?
173             $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
174                 if $suggestion_only->{$date_key};
175         }
176
177         if ( $suggestion_only->{"STATUS"} ) {
178             if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
179                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
180                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
181             }
182             $suggestion_only->{manageddate} = dt_from_string;
183             $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
184         }
185
186         my $otherreason = $input->param('other_reason');
187         if ($suggestion_only->{reason} eq 'other' && $otherreason) {
188             $suggestion_only->{reason} = $otherreason;
189         }
190
191         if ( $suggestion_only->{'suggestionid'} > 0 ) {
192
193             $suggestion_only->{lastmodificationdate} = dt_from_string;
194             $suggestion_only->{lastmodificationby}   = C4::Context->userenv->{number};
195             $suggestion_only->{branchcode} = undef
196               if exists $suggestion_only->{branchcode}
197               && $suggestion_only->{branchcode} eq "";
198
199             &ModSuggestion($suggestion_only);
200
201             if ( $notify ) {
202                 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
203                 my $email_address = $patron->notice_email_address;
204                 if ($patron->notice_email_address) {
205
206                     my $letter = C4::Letters::GetPreparedLetter(
207                         module      => 'suggestions',
208                         letter_code => 'NOTIFY_MANAGER',
209                         branchcode  => $patron->branchcode,
210                         lang        => $patron->lang,
211                         tables      => {
212                             suggestions => $suggestion_only->{suggestionid},
213                             branches    => $patron->branchcode,
214                             borrowers   => $patron->borrowernumber,
215                         },
216                     );
217                     C4::Letters::EnqueueLetter(
218                         {
219                             letter                 => $letter,
220                             borrowernumber         => $patron->borrowernumber,
221                             message_transport_type => 'email'
222                         }
223                     );
224                 }
225             }
226         } else {
227             ###FIXME:Search here if suggestion already exists.
228             my $suggestions= Koha::Suggestions->search_limited( $suggestion_only );
229             if ( $suggestions->count ) {
230                 #some suggestion are answering the request Donot Add
231                 my @messages;
232                 while ( my $suggestion = $suggestions->next ) {
233                     push @messages, { type => 'error', code => 'already_exists', id => $suggestion->suggestionid };
234                 }
235                 $template->param( messages => \@messages );
236             }
237             else {
238                 ## Adding some informations related to suggestion
239                 Koha::Suggestion->new($suggestion_only)->store();
240             }
241             # empty fields, to avoid filter in "SearchSuggestion"
242         }
243         map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
244         $op = 'else';
245
246         if( $redirect eq 'purchase_suggestions' ) {
247             print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
248         }
249     }
250 }
251 elsif ($op=~/add/) {
252     #Adds suggestion
253     Init($suggestion_ref);
254     $op ='save';
255 }
256 elsif ($op=~/edit/) {
257     #Edit suggestion
258     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
259     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
260     $suggestion_ref->{reasonsloop} = $reasonsloop;
261     my $other_reason = 1;
262     foreach my $reason ( @{ $reasonsloop } ) {
263         if ($suggestion_ref->{reason} eq $reason->{lib}) {
264             $other_reason = 0;
265         }
266     }
267     $other_reason = 0 unless $suggestion_ref->{reason};
268     $template->param(other_reason => $other_reason);
269     Init($suggestion_ref);
270     $op ='save';
271 }  
272 elsif ($op eq "update_status" ) {
273     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
274     my $suggestion;
275     # set accepted/rejected/managed informations if applicable
276     # ie= if the librarian has chosen some action on the suggestions
277     my $STATUS      = $input->param('STATUS');
278     my $accepted_by = $input->param('acceptedby');
279     if ( $STATUS eq "ACCEPTED" ) {
280         $suggestion = {
281             accepteddate => dt_from_string,
282             acceptedby => C4::Context->userenv->{number},
283         };
284     }
285     elsif ( $STATUS eq "REJECTED" ) {
286         $suggestion = {
287             rejecteddate => dt_from_string,
288             rejectedby   => C4::Context->userenv->{number},
289         };
290     }
291     if ($STATUS) {
292         $suggestion->{manageddate} = dt_from_string;
293         $suggestion->{managedby}   = C4::Context->userenv->{number};
294         $suggestion->{STATUS}      = $STATUS;
295     }
296     if ( my $reason = $input->param("reason") ) {
297         if ( $reason eq "other" ) {
298             $reason = $input->param("other_reason");
299         }
300         $suggestion->{reason} = $reason;
301     }
302
303     foreach my $suggestionid (@editsuggestions) {
304         next unless $suggestionid;
305         $suggestion->{suggestionid} = $suggestionid;
306         &ModSuggestion($suggestion);
307     }
308     redirect_with_params($input);
309 }elsif ($op eq "delete" ) {
310     output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' });
311     foreach my $delete_field (@editsuggestions) {
312         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
313     }
314     redirect_with_params($input);
315 }
316 elsif ($op eq "archive" ) {
317     Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
318
319     redirect_with_params($input);
320 }
321 elsif ($op eq "unarchive" ) {
322     Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
323
324     redirect_with_params($input);
325 }
326 elsif ( $op eq 'update_itemtype' ) {
327     my $new_itemtype = $input->param('suggestion_itemtype');
328     foreach my $suggestionid (@editsuggestions) {
329         next unless $suggestionid;
330         &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
331     }
332     redirect_with_params($input);
333 }
334 elsif ( $op eq 'update_manager' ) {
335     my $managedby = $input->param('suggestion_managedby');
336     foreach my $suggestionid (@editsuggestions) {
337         next unless $suggestionid;
338         &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
339     }
340     redirect_with_params($input);
341 }
342 elsif ( $op eq 'show' ) {
343     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
344     my $budget = GetBudget $$suggestion_ref{budgetid};
345     $$suggestion_ref{budgetname} = $$budget{budget_name};
346     Init($suggestion_ref);
347 }
348 if ($op=~/else/) {
349     $op='else';
350
351     $displayby||="STATUS";
352     # distinct values of display by
353     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
354     my (@criteria_dv, $criteria_has_empty);
355     foreach (@$criteria_list) {
356         if ($_->{value}) {
357             push @criteria_dv, $_->{value};
358         } else {
359             $criteria_has_empty = 1;
360         }
361     }
362     # aggregate null and empty values under empty value
363     push @criteria_dv, '' if $criteria_has_empty;
364
365     # Hack to not modify GetDistinctValues for this specific case
366     if (   $displayby eq 'branchcode'
367         && C4::Context->preference('IndependentBranches')
368         && not C4::Context->IsSuperLibrarian )
369     {
370         @criteria_dv = ( C4::Context->userenv->{'branch'} );
371     }
372     # Pending tab first
373     if ( $displayby eq 'STATUS' ) {
374         @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv;
375         unshift @criteria_dv, 'ASKED';
376     }
377
378     unless ( exists $suggestion_ref->{branchcode} ) {
379         $suggestion_ref->{branchcode} = C4::Context->userenv->{'branch'};
380     }
381
382     my @allsuggestions;
383     foreach my $criteriumvalue ( @criteria_dv ) {
384         my $search_params = {%$suggestion_ref};
385
386         next
387           if $search_params->{STATUS}
388           && $displayby eq 'STATUS'
389           && $criteriumvalue ne $search_params->{STATUS};
390
391         # By default, display suggestions from current working branch
392         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
393
394         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
395
396         $search_params->{$displayby} = $criteriumvalue;
397
398         # filter on date fields
399         foreach my $field (qw( suggesteddate manageddate accepteddate )) {
400             my $from    = delete $search_params->{"${field}_from"};
401             my $to      = delete $search_params->{"${field}_to"};
402
403             my $from_dt = $from && eval { dt_from_string($from) };
404             my $to_dt   = $to && eval { dt_from_string($to) };
405
406             if ( $from_dt || $to_dt ) {
407                 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
408                 if ( $from_dt && $to_dt ) {
409                     $search_params->{$field} = { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] };
410                 } elsif ( $from_dt ) {
411                     $search_params->{$field} = { '>=' => $dtf->format_date($from_dt) };
412                 } elsif ( $to_dt ) {
413                     $search_params->{$field} = { '<=' => $dtf->format_date($to_dt) };
414                 }
415             }
416         }
417         if ( $search_params->{budgetid} && $search_params->{budgetid} eq '__NONE__' ) {
418             $search_params->{budgetid} = [undef, '' ];
419         }
420         for my $f (qw (branchcode budgetid)) {
421             delete $search_params->{$f}
422               if $search_params->{$f} eq '__ANY__'
423               || $search_params->{$f} eq '';
424         }
425
426         $search_params->{archived} = 0 if !$filter_archived;
427         my @suggestions = Koha::Suggestions->search_limited($search_params)->as_list;
428
429         push @allsuggestions,
430           {
431             "suggestiontype"      => $criteriumvalue || "suggest",
432             "suggestiontypelabel" => GetCriteriumDesc( $criteriumvalue, $displayby ) || "",
433             'suggestions'         => \@suggestions,
434             'reasonsloop'         => $reasonsloop,
435           }
436           if scalar @suggestions > 0;
437
438         delete $$suggestion_ref{$displayby} unless $definedvalue;
439     }
440
441     $template->param(
442         "displayby"=> $displayby,
443         "notabs"=> $displayby eq "",
444         suggestions       => \@allsuggestions,
445     );
446 }
447
448 $template->param(
449     "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
450   for qw(managedby suggestedby acceptedby lastmodificationby);
451
452 $template->param(
453     %$suggestion_ref,
454     filter_archived => $filter_archived,
455     "op"             =>$op,
456 );
457
458 if(defined($returnsuggested) and $returnsuggested ne "noone")
459 {
460     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
461 }
462
463 $template->param(
464     branchfilter => $branchfilter,
465 );
466
467 $template->param( returnsuggestedby => $returnsuggestedby );
468
469 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
470 $template->param(patron_reason_loop=>$patron_reason_loop);
471
472 # Budgets for filtering
473 my $budgets = GetBudgets;
474 my @budgets_loop;
475 foreach my $budget ( @{$budgets} ) {
476     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
477
478     ## Please see file perltidy.ERR
479     $budget->{'selected'} = 1
480         if ($$suggestion_ref{'budgetid'}
481         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
482
483     push @budgets_loop, $budget;
484 }
485 $template->param( budgetsloop => \@budgets_loop);
486
487 # Budgets for suggestion add or edition
488 my $sugg_budget_loop = [];
489 my $sugg_budgets     = GetBudgetHierarchy();
490 foreach my $r ( @{$sugg_budgets} ) {
491     next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
492     my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
493     push @{$sugg_budget_loop},
494       {
495         b_id     => $r->{budget_id},
496         b_txt    => $r->{budget_name},
497         b_active => $r->{budget_period_active},
498         selected => $selected,
499       };
500 }
501 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
502 $template->param( sugg_budgets => $sugg_budget_loop);
503
504 if( $suggestion_ref->{STATUS} ) {
505     $template->param(
506         "statusselected_".$suggestion_ref->{STATUS} => 1,
507         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
508     );
509 }
510
511 my $currencies = Koha::Acquisition::Currencies->search;
512 $template->param(
513     currencies   => $currencies,
514     suggestion   => $suggestion_ref,
515     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
516     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
517 );
518
519 # lists of distinct values (without empty) for filters
520 my %hashlists;
521 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
522     my $values_list;
523     $values_list = GetDistinctValues( "suggestions." . $field );
524     my @codes_list = map {
525         {   'code' => $$_{'value'},
526             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
527             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
528         }
529     } grep {
530         $$_{'value'}
531     } @$values_list;
532     @codes_list = sort { $a->{desc} cmp $b->{desc} } @codes_list;
533     $hashlists{ lc($field) . "_loop" } = \@codes_list;
534 }
535
536 my $csrf_token = Koha::Token->new->generate_csrf(
537     {
538         session_id => scalar $input->cookie('CGISESSID'),
539     }
540 );
541
542 $template->param(
543     %hashlists,
544     borrowernumber     => ( $input->param('borrowernumber') // undef ),
545     SuggestionStatuses => GetAuthorisedValues('SUGGEST_STATUS'),
546     csrf_token         => $csrf_token,
547 );
548 output_html_with_http_headers $input, $cookie, $template->output;
549
550 sub redirect_with_params {
551     my ( $input ) = @_;
552     my $params = '';
553     foreach my $key (
554         qw(
555         displayby branchcode title author isbn publishercode copyrightdate
556         collectiontitle suggestedby suggesteddate_from suggesteddate_to
557         manageddate_from manageddate_to accepteddate_from
558         accepteddate_to budgetid filter_archived
559         )
560       )
561     {
562         $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
563           if defined($input->param($key));
564     }
565     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
566 }