Bug 26621: Adjust .mailmap to reduce the number of invalid authors
[koha.git] / suggestion / suggestion.pl
blobce8a9dee909ad74b036234bef7661a5e773760fa
1 #!/usr/bin/perl
3 # This file is part of Koha.
4 # Copyright 2006-2010 BibLibre
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.
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.
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>.
20 use Modern::Perl;
21 require Exporter;
22 use CGI qw ( -utf8 );
23 use C4::Auth; # get_template_and_user
24 use C4::Output;
25 use C4::Suggestions;
26 use C4::Koha;
27 use C4::Budgets;
28 use C4::Search;
29 use C4::Members;
30 use C4::Debug;
31 use Koha::DateUtils qw( dt_from_string );
32 use Koha::AuthorisedValues;
33 use Koha::Acquisition::Currencies;
34 use Koha::Libraries;
35 use Koha::Patrons;
37 use URI::Escape;
39 sub Init{
40 my $suggestion= shift @_;
41 # "Managed by" is used only when a suggestion is being edited (not when created)
42 if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
43 # new suggestion
44 $suggestion->{suggesteddate} = dt_from_string;
45 $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
47 else {
48 # editing of an existing suggestion
49 $suggestion->{manageddate} = dt_from_string;
50 $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
52 $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
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';
62 return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
64 if ( $displayby =~ /branchcode/ ) {
65 return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
67 if ( $displayby =~ /itemtype/ ) {
68 my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
69 return $av->count ? $av->next->lib : 'Unknown';
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;
76 if ( $displayby =~ /budgetid/) {
77 my $budget = GetBudget($criteriumvalue);
78 return "" unless $budget;
79 return $$budget{budget_name};
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');
98 my $reasonsloop = GetAuthorisedValues("SUGGEST");
100 # filter informations which are not suggestion related.
101 my $suggestion_ref = { %{$input->Vars} }; # Copying, otherwise $input will be modified
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};
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' ));
113 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
115 template_name => "suggestion/suggestion.tt",
116 query => $input,
117 type => "intranet",
118 flagsrequired => { suggestions => 'suggestions_manage' },
122 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
123 $template->param('borrowernumber' => $borrowernumber);
124 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
126 #########################################
127 ## Operations
130 if ( $op =~ /save/i ) {
131 my @messages;
132 my $biblio = MarcRecordFromNewSuggestion({
133 title => $suggestion_only->{title},
134 author => $suggestion_only->{author},
135 itemtype => $suggestion_only->{itemtype},
138 if ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
139 push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
140 $template->param(
141 messages => \@messages,
142 need_confirm => 1
144 delete $suggestion_ref->{suggesteddate};
145 Init($suggestion_ref);
147 else {
149 for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
150 $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
151 if $suggestion_only->{$date_key};
154 if ( $suggestion_only->{"STATUS"} ) {
155 if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
156 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
157 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" } = C4::Context->userenv->{number};
159 $suggestion_only->{manageddate} = dt_from_string;
160 $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
163 my $otherreason = $input->param('other_reason');
164 if ($suggestion_only->{reason} eq 'other' && $otherreason) {
165 $suggestion_only->{reason} = $otherreason;
168 if ( $suggestion_only->{'suggestionid'} > 0 ) {
170 $suggestion_only->{lastmodificationdate} = dt_from_string;
171 $suggestion_only->{lastmodificationby} = C4::Context->userenv->{number};
173 &ModSuggestion($suggestion_only);
175 if ( $notify ) {
176 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
177 my $email_address = $patron->notice_email_address;
178 if ($patron->notice_email_address) {
179 my $library = $patron->library;
180 my $admin_email_address = $library->branchemail
181 || C4::Context->preference('KohaAdminEmailAddress');
183 my $letter = C4::Letters::GetPreparedLetter(
184 module => 'suggestions',
185 letter_code => 'NOTIFY_MANAGER',
186 branchcode => $patron->branchcode,
187 lang => $patron->lang,
188 tables => {
189 suggestions => $suggestion_only->{suggestionid},
190 branches => $patron->branchcode,
191 borrowers => $patron->borrowernumber,
194 C4::Letters::EnqueueLetter(
196 letter => $letter,
197 borrowernumber => $patron->borrowernumber,
198 message_transport_type => 'email',
199 from_address => $admin_email_address,
204 } else {
205 ###FIXME:Search here if suggestion already exists.
206 my $suggestions_loop =
207 SearchSuggestion( $suggestion_only );
208 if (@$suggestions_loop>=1){
209 #some suggestion are answering the request Donot Add
210 my @messages;
211 for my $suggestion ( @$suggestions_loop ) {
212 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
214 $template->param( messages => \@messages );
216 else {
217 ## Adding some informations related to suggestion
218 &NewSuggestion($suggestion_only);
220 # empty fields, to avoid filter in "SearchSuggestion"
222 map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
223 $op = 'else';
225 if( $redirect eq 'purchase_suggestions' ) {
226 print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
230 elsif ($op=~/add/) {
231 #Adds suggestion
232 Init($suggestion_ref);
233 $op ='save';
235 elsif ($op=~/edit/) {
236 #Edit suggestion
237 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
238 $suggestion_ref->{reasonsloop} = $reasonsloop;
239 my $other_reason = 1;
240 foreach my $reason ( @{ $reasonsloop } ) {
241 if ($suggestion_ref->{reason} eq $reason->{lib}) {
242 $other_reason = 0;
245 $other_reason = 0 unless $suggestion_ref->{reason};
246 $template->param(other_reason => $other_reason);
247 Init($suggestion_ref);
248 $op ='save';
250 elsif ($op eq "update_status" ) {
252 my $suggestion;
253 # set accepted/rejected/managed informations if applicable
254 # ie= if the librarian has chosen some action on the suggestions
255 my $STATUS = $input->param('STATUS');
256 my $accepted_by = $input->param('acceptedby');
257 if ( $STATUS eq "ACCEPTED" ) {
258 $suggestion = {
259 accepteddate => dt_from_string,
260 acceptedby => C4::Context->userenv->{number},
263 elsif ( $STATUS eq "REJECTED" ) {
264 $suggestion = {
265 rejecteddate => dt_from_string,
266 rejectedby => C4::Context->userenv->{number},
269 if ($STATUS) {
270 $suggestion->{manageddate} = dt_from_string;
271 $suggestion->{managedby} = C4::Context->userenv->{number};
272 $suggestion->{STATUS} = $STATUS;
274 if ( my $reason = $input->param("reason") ) {
275 if ( $reason eq "other" ) {
276 $reason = $input->param("other_reason");
278 $suggestion->{reason} = $reason;
281 foreach my $suggestionid (@editsuggestions) {
282 next unless $suggestionid;
283 $suggestion->{suggestionid} = $suggestionid;
284 &ModSuggestion($suggestion);
286 redirect_with_params($input);
287 }elsif ($op eq "delete" ) {
288 foreach my $delete_field (@editsuggestions) {
289 &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
291 redirect_with_params($input);
293 elsif ($op eq "archive" ) {
294 Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
296 redirect_with_params($input);
298 elsif ($op eq "unarchive" ) {
299 Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
301 redirect_with_params($input);
303 elsif ( $op eq 'update_itemtype' ) {
304 my $new_itemtype = $input->param('suggestion_itemtype');
305 foreach my $suggestionid (@editsuggestions) {
306 next unless $suggestionid;
307 &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
309 redirect_with_params($input);
311 elsif ( $op eq 'update_manager' ) {
312 my $managedby = $input->param('suggestion_managedby');
313 foreach my $suggestionid (@editsuggestions) {
314 next unless $suggestionid;
315 &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
317 redirect_with_params($input);
319 elsif ( $op eq 'show' ) {
320 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
321 my $budget = GetBudget $$suggestion_ref{budgetid};
322 $$suggestion_ref{budgetname} = $$budget{budget_name};
323 Init($suggestion_ref);
325 if ($op=~/else/) {
326 $op='else';
328 $displayby||="STATUS";
329 # distinct values of display by
330 my $criteria_list=GetDistinctValues("suggestions.".$displayby);
331 my (@criteria_dv, $criteria_has_empty);
332 foreach (@$criteria_list) {
333 if ($_->{value}) {
334 push @criteria_dv, $_->{value};
335 } else {
336 $criteria_has_empty = 1;
339 # aggregate null and empty values under empty value
340 push @criteria_dv, '' if $criteria_has_empty;
342 # Hack to not modify GetDistinctValues for this specific case
343 if ( $displayby eq 'branchcode'
344 && C4::Context->preference('IndependentBranches')
345 && not C4::Context->IsSuperLibrarian )
347 @criteria_dv = ( C4::Context->userenv->{'branch'} );
350 my @allsuggestions;
351 foreach my $criteriumvalue ( @criteria_dv ) {
352 # By default, display suggestions from current working branch
353 unless ( exists $$suggestion_ref{'branchcode'} ) {
354 $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
356 my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
358 next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
359 $$suggestion_ref{$displayby} = $criteriumvalue;
361 my $suggestions = &SearchSuggestion({ %$suggestion_ref, archived => $filter_archived });
362 foreach my $suggestion (@$suggestions) {
363 if ($suggestion->{budgetid}){
364 my $bud = GetBudget( $suggestion->{budgetid} );
365 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
368 push @allsuggestions,{
369 "suggestiontype"=>$criteriumvalue||"suggest",
370 "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
371 "suggestionscount"=>scalar(@$suggestions),
372 'suggestions_loop'=>$suggestions,
373 'reasonsloop' => $reasonsloop,
374 } if @$suggestions;
376 delete $$suggestion_ref{$displayby} unless $definedvalue;
379 $template->param(
380 "displayby"=> $displayby,
381 "notabs"=> $displayby eq "",
382 suggestions => \@allsuggestions,
386 $template->param(
387 "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
388 for qw(managedby suggestedby acceptedby lastmodificationby);
390 $template->param(
391 %$suggestion_ref,
392 filter_archived => $filter_archived,
393 "op" =>$op,
396 if(defined($returnsuggested) and $returnsuggested ne "noone")
398 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
401 $template->param(
402 branchfilter => $branchfilter,
405 $template->param( returnsuggestedby => $returnsuggestedby );
407 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
408 $template->param(patron_reason_loop=>$patron_reason_loop);
410 # Budgets for filtering
411 my $budgets = GetBudgets;
412 my @budgets_loop;
413 foreach my $budget ( @{$budgets} ) {
414 next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
416 ## Please see file perltidy.ERR
417 $budget->{'selected'} = 1
418 if ($$suggestion_ref{'budgetid'}
419 && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
421 push @budgets_loop, $budget;
423 $template->param( budgetsloop => \@budgets_loop);
425 # Budgets for suggestion add or edition
426 my $sugg_budget_loop = [];
427 my $sugg_budgets = GetBudgetHierarchy();
428 foreach my $r ( @{$sugg_budgets} ) {
429 next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
430 my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
431 push @{$sugg_budget_loop},
433 b_id => $r->{budget_id},
434 b_txt => $r->{budget_name},
435 b_active => $r->{budget_period_active},
436 selected => $selected,
439 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
440 $template->param( sugg_budgets => $sugg_budget_loop);
442 if( $suggestion_ref->{STATUS} ) {
443 $template->param(
444 "statusselected_".$suggestion_ref->{STATUS} => 1,
445 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
449 my @currencies = Koha::Acquisition::Currencies->search;
450 $template->param(
451 currencies => \@currencies,
452 suggestion => $suggestion_ref,
453 price => sprintf("%.2f", $$suggestion_ref{'price'}||0),
454 total => sprintf("%.2f", $$suggestion_ref{'total'}||0),
457 # lists of distinct values (without empty) for filters
458 my %hashlists;
459 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
460 my $values_list;
461 $values_list = GetDistinctValues( "suggestions." . $field );
462 my @codes_list = map {
463 { 'code' => $$_{'value'},
464 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
465 'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
467 } grep {
468 $$_{'value'}
469 } @$values_list;
470 $hashlists{ lc($field) . "_loop" } = \@codes_list;
473 $template->param(
474 %hashlists,
475 borrowernumber => ($input->param('borrowernumber') // undef),
476 SuggestionStatuses => GetAuthorisedValues('SUGGEST_STATUS'),
478 output_html_with_http_headers $input, $cookie, $template->output;
480 sub redirect_with_params {
481 my ( $input ) = @_;
482 my $params = '';
483 foreach my $key (
485 displayby branchcode title author isbn publishercode copyrightdate
486 collectiontitle suggestedby suggesteddate_from suggesteddate_to
487 manageddate_from manageddate_to accepteddate_from
488 accepteddate_to budgetid filter_archived
492 $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
493 if defined($input->param($key));
495 print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");