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