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