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