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') || 0;
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 delete $suggestion_only->{branchcode} if $suggestion_only->{branchcode} eq '__ANY__';
113 delete $suggestion_only->{budgetid} if $suggestion_only->{budgetid} eq '__ANY__';
114 while ( my ( $k, $v ) = each %$suggestion_only ) {
115 delete $suggestion_only->{$k} if $v eq '';
118 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
120 template_name => "suggestion/suggestion.tt",
123 flagsrequired => { suggestions => 'suggestions_manage' },
127 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
128 $template->param('borrowernumber' => $borrowernumber);
129 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
131 #########################################
135 if ( $op =~ /save/i ) {
137 my $biblio = MarcRecordFromNewSuggestion({
138 title => $suggestion_only->{title},
139 author => $suggestion_only->{author},
140 itemtype => $suggestion_only->{itemtype},
141 isbn => $suggestion_only->{isbn},
144 my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
145 if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
146 push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
148 messages => \@messages,
150 delete $suggestion_ref->{suggesteddate};
151 delete $suggestion_ref->{manageddate};
152 delete $suggestion_ref->{managedby};
153 Init($suggestion_ref);
155 elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
156 push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
158 messages => \@messages,
161 delete $suggestion_ref->{suggesteddate};
162 delete $suggestion_ref->{manageddate};
163 Init($suggestion_ref);
167 for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
168 $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
169 if $suggestion_only->{$date_key};
172 if ( $suggestion_only->{"STATUS"} ) {
173 if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
174 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
175 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" } = C4::Context->userenv->{number};
177 $suggestion_only->{manageddate} = dt_from_string;
178 $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
181 my $otherreason = $input->param('other_reason');
182 if ($suggestion_only->{reason} eq 'other' && $otherreason) {
183 $suggestion_only->{reason} = $otherreason;
186 if ( $suggestion_only->{'suggestionid'} > 0 ) {
188 $suggestion_only->{lastmodificationdate} = dt_from_string;
189 $suggestion_only->{lastmodificationby} = C4::Context->userenv->{number};
190 $suggestion_only->{branchcode} = undef
191 if exists $suggestion_only->{branchcode}
192 && $suggestion_only->{branchcode} eq "";
194 &ModSuggestion($suggestion_only);
197 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
198 my $email_address = $patron->notice_email_address;
199 if ($patron->notice_email_address) {
201 my $letter = C4::Letters::GetPreparedLetter(
202 module => 'suggestions',
203 letter_code => 'NOTIFY_MANAGER',
204 branchcode => $patron->branchcode,
205 lang => $patron->lang,
207 suggestions => $suggestion_only->{suggestionid},
208 branches => $patron->branchcode,
209 borrowers => $patron->borrowernumber,
212 C4::Letters::EnqueueLetter(
215 borrowernumber => $patron->borrowernumber,
216 message_transport_type => 'email'
222 ###FIXME:Search here if suggestion already exists.
223 my $suggestions= Koha::Suggestions->search_limited( $suggestion_only );
224 if ( $suggestions->count ) {
225 #some suggestion are answering the request Donot Add
227 while ( my $suggestion = $suggestions->next ) {
228 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->suggestionid };
230 $template->param( messages => \@messages );
233 ## Adding some informations related to suggestion
234 &NewSuggestion($suggestion_only);
236 # empty fields, to avoid filter in "SearchSuggestion"
238 map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
241 if( $redirect eq 'purchase_suggestions' ) {
242 print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
248 Init($suggestion_ref);
251 elsif ($op=~/edit/) {
253 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
254 $suggestion_ref->{reasonsloop} = $reasonsloop;
255 my $other_reason = 1;
256 foreach my $reason ( @{ $reasonsloop } ) {
257 if ($suggestion_ref->{reason} eq $reason->{lib}) {
261 $other_reason = 0 unless $suggestion_ref->{reason};
262 $template->param(other_reason => $other_reason);
263 Init($suggestion_ref);
266 elsif ($op eq "update_status" ) {
269 # set accepted/rejected/managed informations if applicable
270 # ie= if the librarian has chosen some action on the suggestions
271 my $STATUS = $input->param('STATUS');
272 my $accepted_by = $input->param('acceptedby');
273 if ( $STATUS eq "ACCEPTED" ) {
275 accepteddate => dt_from_string,
276 acceptedby => C4::Context->userenv->{number},
279 elsif ( $STATUS eq "REJECTED" ) {
281 rejecteddate => dt_from_string,
282 rejectedby => C4::Context->userenv->{number},
286 $suggestion->{manageddate} = dt_from_string;
287 $suggestion->{managedby} = C4::Context->userenv->{number};
288 $suggestion->{STATUS} = $STATUS;
290 if ( my $reason = $input->param("reason") ) {
291 if ( $reason eq "other" ) {
292 $reason = $input->param("other_reason");
294 $suggestion->{reason} = $reason;
297 foreach my $suggestionid (@editsuggestions) {
298 next unless $suggestionid;
299 $suggestion->{suggestionid} = $suggestionid;
300 &ModSuggestion($suggestion);
302 redirect_with_params($input);
303 }elsif ($op eq "delete" ) {
304 foreach my $delete_field (@editsuggestions) {
305 &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
307 redirect_with_params($input);
309 elsif ($op eq "archive" ) {
310 Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
312 redirect_with_params($input);
314 elsif ($op eq "unarchive" ) {
315 Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
317 redirect_with_params($input);
319 elsif ( $op eq 'update_itemtype' ) {
320 my $new_itemtype = $input->param('suggestion_itemtype');
321 foreach my $suggestionid (@editsuggestions) {
322 next unless $suggestionid;
323 &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
325 redirect_with_params($input);
327 elsif ( $op eq 'update_manager' ) {
328 my $managedby = $input->param('suggestion_managedby');
329 foreach my $suggestionid (@editsuggestions) {
330 next unless $suggestionid;
331 &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
333 redirect_with_params($input);
335 elsif ( $op eq 'show' ) {
336 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
337 my $budget = GetBudget $$suggestion_ref{budgetid};
338 $$suggestion_ref{budgetname} = $$budget{budget_name};
339 Init($suggestion_ref);
344 $displayby||="STATUS";
345 # distinct values of display by
346 my $criteria_list=GetDistinctValues("suggestions.".$displayby);
347 my (@criteria_dv, $criteria_has_empty);
348 foreach (@$criteria_list) {
350 push @criteria_dv, $_->{value};
352 $criteria_has_empty = 1;
355 # aggregate null and empty values under empty value
356 push @criteria_dv, '' if $criteria_has_empty;
358 # Hack to not modify GetDistinctValues for this specific case
359 if ( $displayby eq 'branchcode'
360 && C4::Context->preference('IndependentBranches')
361 && not C4::Context->IsSuperLibrarian )
363 @criteria_dv = ( C4::Context->userenv->{'branch'} );
366 if ( $displayby eq 'STATUS' ) {
367 @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv;
368 unshift @criteria_dv, 'ASKED';
371 unless ( exists $suggestion_ref->{branchcode} ) {
372 $suggestion_ref->{branchcode} = C4::Context->userenv->{'branch'};
376 foreach my $criteriumvalue ( @criteria_dv ) {
377 my $search_params = {%$suggestion_ref};
378 # By default, display suggestions from current working branch
379 my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
381 next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
383 $search_params->{$displayby} = $criteriumvalue;
385 # filter on date fields
386 foreach my $field (qw( suggesteddate manageddate accepteddate )) {
387 my $from = delete $search_params->{"${field}_from"};
388 my $to = delete $search_params->{"${field}_to"};
390 my $from_dt = $from && eval { dt_from_string($from) };
391 my $to_dt = $to && eval { dt_from_string($to) };
393 if ( $from_dt || $to_dt ) {
394 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
395 if ( $from_dt && $to_dt ) {
396 $search_params->{$field} = { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] };
397 } elsif ( $from_dt ) {
398 $search_params->{$field} = { '>=' => $dtf->format_date($from_dt) };
400 $search_params->{$field} = { '<=' => $dtf->format_date($to_dt) };
404 if ( $search_params->{budgetid} && $search_params->{budgetid} eq '__NONE__' ) {
405 $search_params->{budgetid} = [undef, '' ];
407 for my $f (qw (branchcode budgetid)) {
408 delete $search_params->{$f}
409 if $search_params->{$f} eq '__ANY__'
410 || $search_params->{$f} eq '';
414 Koha::Suggestions->search_limited(
415 { %$search_params, archived => $filter_archived } )->as_list;
417 push @allsuggestions,
419 "suggestiontype" => $criteriumvalue || "suggest",
420 "suggestiontypelabel" => GetCriteriumDesc( $criteriumvalue, $displayby ) || "",
421 'suggestions' => \@suggestions,
422 'reasonsloop' => $reasonsloop,
424 if scalar @suggestions > 0;
426 delete $$suggestion_ref{$displayby} unless $definedvalue;
430 "displayby"=> $displayby,
431 "notabs"=> $displayby eq "",
432 suggestions => \@allsuggestions,
437 "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
438 for qw(managedby suggestedby acceptedby lastmodificationby);
442 filter_archived => $filter_archived,
446 if(defined($returnsuggested) and $returnsuggested ne "noone")
448 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
452 branchfilter => $branchfilter,
455 $template->param( returnsuggestedby => $returnsuggestedby );
457 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
458 $template->param(patron_reason_loop=>$patron_reason_loop);
460 # Budgets for filtering
461 my $budgets = GetBudgets;
463 foreach my $budget ( @{$budgets} ) {
464 next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
466 ## Please see file perltidy.ERR
467 $budget->{'selected'} = 1
468 if ($$suggestion_ref{'budgetid'}
469 && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
471 push @budgets_loop, $budget;
473 $template->param( budgetsloop => \@budgets_loop);
475 # Budgets for suggestion add or edition
476 my $sugg_budget_loop = [];
477 my $sugg_budgets = GetBudgetHierarchy();
478 foreach my $r ( @{$sugg_budgets} ) {
479 next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
480 my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
481 push @{$sugg_budget_loop},
483 b_id => $r->{budget_id},
484 b_txt => $r->{budget_name},
485 b_active => $r->{budget_period_active},
486 selected => $selected,
489 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
490 $template->param( sugg_budgets => $sugg_budget_loop);
492 if( $suggestion_ref->{STATUS} ) {
494 "statusselected_".$suggestion_ref->{STATUS} => 1,
495 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
499 my $currencies = Koha::Acquisition::Currencies->search;
501 currencies => $currencies,
502 suggestion => $suggestion_ref,
503 price => sprintf("%.2f", $$suggestion_ref{'price'}||0),
504 total => sprintf("%.2f", $$suggestion_ref{'total'}||0),
507 # lists of distinct values (without empty) for filters
509 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
511 $values_list = GetDistinctValues( "suggestions." . $field );
512 my @codes_list = map {
513 { 'code' => $$_{'value'},
514 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
515 'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
520 $hashlists{ lc($field) . "_loop" } = \@codes_list;
525 borrowernumber => ($input->param('borrowernumber') // undef),
526 SuggestionStatuses => GetAuthorisedValues('SUGGEST_STATUS'),
528 output_html_with_http_headers $input, $cookie, $template->output;
530 sub redirect_with_params {
535 displayby branchcode title author isbn publishercode copyrightdate
536 collectiontitle suggestedby suggesteddate_from suggesteddate_to
537 manageddate_from manageddate_to accepteddate_from
538 accepteddate_to budgetid filter_archived
542 $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
543 if defined($input->param($key));
545 print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");