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>.
23 use C4::Auth qw( get_template_and_user );
24 use C4::Output qw( output_html_with_http_headers );
26 use C4::Koha qw( GetAuthorisedValues );
27 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget );
28 use C4::Search qw( FindDuplicate GetDistinctValues );
30 use Koha::DateUtils qw( dt_from_string );
31 use Koha::AuthorisedValues;
32 use Koha::Acquisition::Currencies;
36 use URI::Escape qw( uri_escape );
39 my $suggestion= shift @_;
40 # "Managed by" is used only when a suggestion is being edited (not when created)
41 if ($suggestion->{'suggesteddate'} eq "") {
43 $suggestion->{suggesteddate} = dt_from_string;
44 $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
47 # editing of an existing suggestion
48 $suggestion->{manageddate} = dt_from_string;
49 $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
51 $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
55 my ($criteriumvalue,$displayby)=@_;
56 if ($displayby =~ /status/i) {
57 unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
58 my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
59 return $av->count ? $av->next->lib : 'Unknown';
61 return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
63 if ( $displayby =~ /branchcode/ ) {
64 return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
66 if ( $displayby =~ /itemtype/ ) {
67 my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
68 return $av->count ? $av->next->lib : 'Unknown';
70 if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
71 my $patron = Koha::Patrons->find( $criteriumvalue );
72 return "" unless $patron;
73 return $patron->surname . ", " . $patron->firstname;
75 if ( $displayby =~ /budgetid/) {
76 my $budget = GetBudget($criteriumvalue);
77 return "" unless $budget;
78 return $$budget{budget_name};
83 my $redirect = $input->param('redirect');
84 my $suggestedbyme = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
85 my $op = $input->param('op')||'else';
86 my @editsuggestions = $input->multi_param('suggestionid');
87 my $suggestedby = $input->param('suggestedby');
88 my $returnsuggestedby = $input->param('returnsuggestedby');
89 my $returnsuggested = $input->param('returnsuggested');
90 my $managedby = $input->param('managedby');
91 my $displayby = $input->param('displayby') || '';
92 my $tabcode = $input->param('tabcode');
93 my $save_confirmed = $input->param('save_confirmed') || 0;
94 my $notify = $input->param('notify');
95 my $filter_archived = $input->param('filter_archived');
97 my $reasonsloop = GetAuthorisedValues("SUGGEST");
99 # filter informations which are not suggestion related.
100 my $suggestion_ref = { %{$input->Vars} }; # Copying, otherwise $input will be modified
102 # get only the columns of Suggestion
103 my $schema = Koha::Database->new()->schema;
104 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
105 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
106 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
108 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode notify filter_archived );
109 foreach (keys %$suggestion_ref){
110 delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
112 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
114 template_name => "suggestion/suggestion.tt",
117 flagsrequired => { suggestions => 'suggestions_manage' },
121 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
122 $template->param('borrowernumber' => $borrowernumber);
123 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
125 #########################################
129 if ( $op =~ /save/i ) {
131 my $biblio = MarcRecordFromNewSuggestion({
132 title => $suggestion_only->{title},
133 author => $suggestion_only->{author},
134 itemtype => $suggestion_only->{itemtype},
137 my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
138 if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
139 push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
141 messages => \@messages,
143 delete $suggestion_ref->{suggesteddate};
144 delete $suggestion_ref->{manageddate};
145 delete $suggestion_ref->{managedby};
146 Init($suggestion_ref);
148 elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
149 push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
151 messages => \@messages,
154 delete $suggestion_ref->{suggesteddate};
155 delete $suggestion_ref->{manageddate};
156 Init($suggestion_ref);
160 for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
161 $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
162 if $suggestion_only->{$date_key};
165 if ( $suggestion_only->{"STATUS"} ) {
166 if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
167 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
168 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" } = C4::Context->userenv->{number};
170 $suggestion_only->{manageddate} = dt_from_string;
171 $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
174 my $otherreason = $input->param('other_reason');
175 if ($suggestion_only->{reason} eq 'other' && $otherreason) {
176 $suggestion_only->{reason} = $otherreason;
179 if ( $suggestion_only->{'suggestionid'} > 0 ) {
181 $suggestion_only->{lastmodificationdate} = dt_from_string;
182 $suggestion_only->{lastmodificationby} = C4::Context->userenv->{number};
184 &ModSuggestion($suggestion_only);
187 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
188 my $email_address = $patron->notice_email_address;
189 if ($patron->notice_email_address) {
191 my $letter = C4::Letters::GetPreparedLetter(
192 module => 'suggestions',
193 letter_code => 'NOTIFY_MANAGER',
194 branchcode => $patron->branchcode,
195 lang => $patron->lang,
197 suggestions => $suggestion_only->{suggestionid},
198 branches => $patron->branchcode,
199 borrowers => $patron->borrowernumber,
202 C4::Letters::EnqueueLetter(
205 borrowernumber => $patron->borrowernumber,
206 message_transport_type => 'email'
212 ###FIXME:Search here if suggestion already exists.
213 my $suggestions_loop =
214 SearchSuggestion( $suggestion_only );
215 if (@$suggestions_loop>=1){
216 #some suggestion are answering the request Donot Add
218 for my $suggestion ( @$suggestions_loop ) {
219 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
221 $template->param( messages => \@messages );
224 ## Adding some informations related to suggestion
225 &NewSuggestion($suggestion_only);
227 # empty fields, to avoid filter in "SearchSuggestion"
229 map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
232 if( $redirect eq 'purchase_suggestions' ) {
233 print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
239 Init($suggestion_ref);
242 elsif ($op=~/edit/) {
244 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
245 $suggestion_ref->{reasonsloop} = $reasonsloop;
246 my $other_reason = 1;
247 foreach my $reason ( @{ $reasonsloop } ) {
248 if ($suggestion_ref->{reason} eq $reason->{lib}) {
252 $other_reason = 0 unless $suggestion_ref->{reason};
253 $template->param(other_reason => $other_reason);
254 Init($suggestion_ref);
257 elsif ($op eq "update_status" ) {
260 # set accepted/rejected/managed informations if applicable
261 # ie= if the librarian has chosen some action on the suggestions
262 my $STATUS = $input->param('STATUS');
263 my $accepted_by = $input->param('acceptedby');
264 if ( $STATUS eq "ACCEPTED" ) {
266 accepteddate => dt_from_string,
267 acceptedby => C4::Context->userenv->{number},
270 elsif ( $STATUS eq "REJECTED" ) {
272 rejecteddate => dt_from_string,
273 rejectedby => C4::Context->userenv->{number},
277 $suggestion->{manageddate} = dt_from_string;
278 $suggestion->{managedby} = C4::Context->userenv->{number};
279 $suggestion->{STATUS} = $STATUS;
281 if ( my $reason = $input->param("reason") ) {
282 if ( $reason eq "other" ) {
283 $reason = $input->param("other_reason");
285 $suggestion->{reason} = $reason;
288 foreach my $suggestionid (@editsuggestions) {
289 next unless $suggestionid;
290 $suggestion->{suggestionid} = $suggestionid;
291 &ModSuggestion($suggestion);
293 redirect_with_params($input);
294 }elsif ($op eq "delete" ) {
295 foreach my $delete_field (@editsuggestions) {
296 &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
298 redirect_with_params($input);
300 elsif ($op eq "archive" ) {
301 Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
303 redirect_with_params($input);
305 elsif ($op eq "unarchive" ) {
306 Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
308 redirect_with_params($input);
310 elsif ( $op eq 'update_itemtype' ) {
311 my $new_itemtype = $input->param('suggestion_itemtype');
312 foreach my $suggestionid (@editsuggestions) {
313 next unless $suggestionid;
314 &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
316 redirect_with_params($input);
318 elsif ( $op eq 'update_manager' ) {
319 my $managedby = $input->param('suggestion_managedby');
320 foreach my $suggestionid (@editsuggestions) {
321 next unless $suggestionid;
322 &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
324 redirect_with_params($input);
326 elsif ( $op eq 'show' ) {
327 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
328 my $budget = GetBudget $$suggestion_ref{budgetid};
329 $$suggestion_ref{budgetname} = $$budget{budget_name};
330 Init($suggestion_ref);
335 $displayby||="STATUS";
336 # distinct values of display by
337 my $criteria_list=GetDistinctValues("suggestions.".$displayby);
338 my (@criteria_dv, $criteria_has_empty);
339 foreach (@$criteria_list) {
341 push @criteria_dv, $_->{value};
343 $criteria_has_empty = 1;
346 # aggregate null and empty values under empty value
347 push @criteria_dv, '' if $criteria_has_empty;
349 # Hack to not modify GetDistinctValues for this specific case
350 if ( $displayby eq 'branchcode'
351 && C4::Context->preference('IndependentBranches')
352 && not C4::Context->IsSuperLibrarian )
354 @criteria_dv = ( C4::Context->userenv->{'branch'} );
358 foreach my $criteriumvalue ( @criteria_dv ) {
359 # By default, display suggestions from current working branch
360 unless ( exists $$suggestion_ref{'branchcode'} ) {
361 $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
363 my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
365 next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
366 $$suggestion_ref{$displayby} = $criteriumvalue;
368 my $suggestions = &SearchSuggestion({ %$suggestion_ref, archived => $filter_archived });
369 foreach my $suggestion (@$suggestions) {
370 if ($suggestion->{budgetid}){
371 my $bud = GetBudget( $suggestion->{budgetid} );
372 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
375 push @allsuggestions,{
376 "suggestiontype"=>$criteriumvalue||"suggest",
377 "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
378 "suggestionscount"=>scalar(@$suggestions),
379 'suggestions_loop'=>$suggestions,
380 'reasonsloop' => $reasonsloop,
383 delete $$suggestion_ref{$displayby} unless $definedvalue;
387 "displayby"=> $displayby,
388 "notabs"=> $displayby eq "",
389 suggestions => \@allsuggestions,
394 "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
395 for qw(managedby suggestedby acceptedby lastmodificationby);
399 filter_archived => $filter_archived,
403 if(defined($returnsuggested) and $returnsuggested ne "noone")
405 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
409 branchfilter => $branchfilter,
412 $template->param( returnsuggestedby => $returnsuggestedby );
414 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
415 $template->param(patron_reason_loop=>$patron_reason_loop);
417 # Budgets for filtering
418 my $budgets = GetBudgets;
420 foreach my $budget ( @{$budgets} ) {
421 next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
423 ## Please see file perltidy.ERR
424 $budget->{'selected'} = 1
425 if ($$suggestion_ref{'budgetid'}
426 && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
428 push @budgets_loop, $budget;
430 $template->param( budgetsloop => \@budgets_loop);
432 # Budgets for suggestion add or edition
433 my $sugg_budget_loop = [];
434 my $sugg_budgets = GetBudgetHierarchy();
435 foreach my $r ( @{$sugg_budgets} ) {
436 next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
437 my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
438 push @{$sugg_budget_loop},
440 b_id => $r->{budget_id},
441 b_txt => $r->{budget_name},
442 b_active => $r->{budget_period_active},
443 selected => $selected,
446 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
447 $template->param( sugg_budgets => $sugg_budget_loop);
449 if( $suggestion_ref->{STATUS} ) {
451 "statusselected_".$suggestion_ref->{STATUS} => 1,
452 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
456 my @currencies = Koha::Acquisition::Currencies->search;
458 currencies => \@currencies,
459 suggestion => $suggestion_ref,
460 price => sprintf("%.2f", $$suggestion_ref{'price'}||0),
461 total => sprintf("%.2f", $$suggestion_ref{'total'}||0),
464 # lists of distinct values (without empty) for filters
466 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
468 $values_list = GetDistinctValues( "suggestions." . $field );
469 my @codes_list = map {
470 { 'code' => $$_{'value'},
471 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
472 'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
477 $hashlists{ lc($field) . "_loop" } = \@codes_list;
482 borrowernumber => ($input->param('borrowernumber') // undef),
483 SuggestionStatuses => GetAuthorisedValues('SUGGEST_STATUS'),
485 output_html_with_http_headers $input, $cookie, $template->output;
487 sub redirect_with_params {
492 displayby branchcode title author isbn publishercode copyrightdate
493 collectiontitle suggestedby suggesteddate_from suggesteddate_to
494 manageddate_from manageddate_to accepteddate_from
495 accepteddate_to budgetid filter_archived
499 $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
500 if defined($input->param($key));
502 print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");