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 output_and_exit_if_error );
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;
35 use Koha::Suggestions;
38 use URI::Escape qw( uri_escape );
41 my $suggestion= shift @_;
42 # "Managed by" is used only when a suggestion is being edited (not when created)
43 if ($suggestion->{'suggesteddate'} eq "") {
45 $suggestion->{suggesteddate} = dt_from_string;
46 $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
49 # editing of an existing suggestion
50 $suggestion->{manageddate} = dt_from_string;
51 $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
53 $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
57 my ($criteriumvalue,$displayby)=@_;
58 if ($displayby =~ /status/i) {
59 unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
60 my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
61 return $av->count ? $av->next->lib : 'Unknown';
63 return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
65 if ( $displayby =~ /branchcode/ ) {
66 return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
68 if ( $displayby =~ /itemtype/ ) {
69 my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
70 return $av->count ? $av->next->lib : 'Unknown';
72 if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
73 my $patron = Koha::Patrons->find( $criteriumvalue );
74 return "" unless $patron;
75 return $patron->surname . ", " . $patron->firstname;
77 if ( $displayby =~ /budgetid/) {
78 my $budget = GetBudget($criteriumvalue);
79 return "" unless $budget;
80 return $$budget{budget_name};
85 my $redirect = $input->param('redirect');
86 my $suggestedbyme = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
87 my $op = $input->param('op')||'else';
88 my @editsuggestions = $input->multi_param('suggestionid');
89 my $suggestedby = $input->param('suggestedby');
90 my $returnsuggestedby = $input->param('returnsuggestedby');
91 my $returnsuggested = $input->param('returnsuggested');
92 my $managedby = $input->param('managedby');
93 my $displayby = $input->param('displayby') || '';
94 my $tabcode = $input->param('tabcode');
95 my $save_confirmed = $input->param('save_confirmed') || 0;
96 my $notify = $input->param('notify');
97 my $filter_archived = $input->param('filter_archived') || 0;
98 my $new_itemtype = $input->param('suggestion_itemtype');
99 my $sugg_managedby = $input->param('suggestion_managedby');
101 my $reasonsloop = GetAuthorisedValues("SUGGEST");
103 my $suggestion_ref = { $input->Vars };
104 delete $suggestion_ref->{$_} for qw(csrf_token suggestion_itemtype suggestion_managedby table_1_length);
106 # get only the columns of Suggestion
107 my $schema = Koha::Database->new()->schema;
108 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
109 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
110 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
112 delete $$suggestion_ref{$_}
114 qw( suggestedbyme op displayby tabcode notify filter_archived koha_login_context auth_forwarded_hash password userid );
115 foreach (keys %$suggestion_ref){
116 delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
118 delete $suggestion_only->{branchcode} if $suggestion_only->{branchcode} eq '__ANY__';
119 delete $suggestion_only->{budgetid} if $suggestion_only->{budgetid} eq '__ANY__';
120 while ( my ( $k, $v ) = each %$suggestion_only ) {
121 delete $suggestion_only->{$k} if $v eq '';
124 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
126 template_name => "suggestion/suggestion.tt",
129 flagsrequired => { suggestions => 'suggestions_manage' },
133 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
134 $template->param('borrowernumber' => $borrowernumber);
135 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
137 #########################################
141 if ( $op =~ /cud-save/ ) {
143 my $biblio = MarcRecordFromNewSuggestion({
144 title => $suggestion_only->{title},
145 author => $suggestion_only->{author},
146 itemtype => $suggestion_only->{itemtype},
147 isbn => $suggestion_only->{isbn},
150 my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
151 if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
152 push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
154 messages => \@messages,
156 delete $suggestion_ref->{suggesteddate};
157 delete $suggestion_ref->{manageddate};
158 delete $suggestion_ref->{managedby};
159 Init($suggestion_ref);
161 elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
162 push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
164 messages => \@messages,
167 delete $suggestion_ref->{suggesteddate};
168 delete $suggestion_ref->{manageddate};
169 Init($suggestion_ref);
173 for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
174 # FIXME Do we need this?
175 $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
176 if $suggestion_only->{$date_key};
179 if ( $suggestion_only->{"STATUS"} ) {
180 if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
181 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
182 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" } = C4::Context->userenv->{number};
184 $suggestion_only->{manageddate} = dt_from_string;
185 $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
188 my $otherreason = $input->param('other_reason');
189 if ($suggestion_only->{reason} eq 'other' && $otherreason) {
190 $suggestion_only->{reason} = $otherreason;
193 if ( $suggestion_only->{'suggestionid'} > 0 ) {
195 $suggestion_only->{lastmodificationdate} = dt_from_string;
196 $suggestion_only->{lastmodificationby} = C4::Context->userenv->{number};
197 $suggestion_only->{branchcode} = undef
198 if exists $suggestion_only->{branchcode}
199 && $suggestion_only->{branchcode} eq "";
201 &ModSuggestion($suggestion_only);
204 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
205 my $email_address = $patron->notice_email_address;
206 if ($patron->notice_email_address) {
208 my $letter = C4::Letters::GetPreparedLetter(
209 module => 'suggestions',
210 letter_code => 'NOTIFY_MANAGER',
211 branchcode => $patron->branchcode,
212 lang => $patron->lang,
214 suggestions => $suggestion_only->{suggestionid},
215 branches => $patron->branchcode,
216 borrowers => $patron->borrowernumber,
219 C4::Letters::EnqueueLetter(
222 borrowernumber => $patron->borrowernumber,
223 message_transport_type => 'email'
229 ###FIXME:Search here if suggestion already exists.
230 my $suggestions= Koha::Suggestions->search_limited( $suggestion_only );
231 if ( $suggestions->count ) {
232 #some suggestion are answering the request Donot Add
234 while ( my $suggestion = $suggestions->next ) {
235 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->suggestionid };
237 $template->param( messages => \@messages );
240 ## Adding some informations related to suggestion
241 Koha::Suggestion->new($suggestion_only)->store();
243 # empty fields, to avoid filter in "SearchSuggestion"
245 map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
248 if( $redirect eq 'purchase_suggestions' ) {
249 print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
253 elsif ( $op eq 'add_form' ) {
255 Init($suggestion_ref);
258 elsif ( $op eq 'edit_form' ) {
260 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
261 $suggestion_ref->{reasonsloop} = $reasonsloop;
262 my $other_reason = 1;
263 foreach my $reason ( @{ $reasonsloop } ) {
264 if ($suggestion_ref->{reason} eq $reason->{lib}) {
268 $other_reason = 0 unless $suggestion_ref->{reason};
269 $template->param(other_reason => $other_reason);
270 Init($suggestion_ref);
273 elsif ($op eq "cud-update_status" ) {
275 # set accepted/rejected/managed informations if applicable
276 # ie= if the librarian has chosen some action on the suggestions
277 my $STATUS = $input->param('STATUS');
278 my $accepted_by = $input->param('acceptedby');
279 if ( $STATUS eq "ACCEPTED" ) {
281 accepteddate => dt_from_string,
282 acceptedby => C4::Context->userenv->{number},
285 elsif ( $STATUS eq "REJECTED" ) {
287 rejecteddate => dt_from_string,
288 rejectedby => C4::Context->userenv->{number},
292 $suggestion->{manageddate} = dt_from_string;
293 $suggestion->{managedby} = C4::Context->userenv->{number};
294 $suggestion->{STATUS} = $STATUS;
296 if ( my $reason = $input->param("reason") ) {
297 if ( $reason eq "other" ) {
298 $reason = $input->param("other_reason");
300 $suggestion->{reason} = $reason;
303 foreach my $suggestionid (@editsuggestions) {
304 next unless $suggestionid;
305 $suggestion->{suggestionid} = $suggestionid;
306 &ModSuggestion($suggestion);
308 redirect_with_params($input);
309 }elsif ($op eq "cud-delete" ) {
310 foreach my $delete_field (@editsuggestions) {
311 &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
313 redirect_with_params($input);
315 elsif ($op eq "cud-archive" ) {
316 Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
317 redirect_with_params($input);
319 elsif ($op eq "cud-unarchive" ) {
320 Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
321 redirect_with_params($input);
323 elsif ( $op eq 'cud-update_itemtype' ) {
324 foreach my $suggestionid (@editsuggestions) {
325 next unless $suggestionid;
326 &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
328 redirect_with_params($input);
330 elsif ( $op eq 'cud-update_manager' ) {
331 foreach my $suggestionid (@editsuggestions) {
332 next unless $suggestionid;
333 &ModSuggestion({ suggestionid => $suggestionid, managedby => $sugg_managedby });
335 redirect_with_params($input);
337 elsif ( $op eq 'show' ) {
338 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
339 my $budget = GetBudget $$suggestion_ref{budgetid};
340 $$suggestion_ref{budgetname} = $$budget{budget_name};
341 Init($suggestion_ref);
344 if ( $op eq 'else' ) {
346 $displayby||="STATUS";
347 # distinct values of display by
348 my $criteria_list=GetDistinctValues("suggestions.".$displayby);
349 my (@criteria_dv, $criteria_has_empty);
350 foreach (@$criteria_list) {
352 push @criteria_dv, $_->{value};
354 $criteria_has_empty = 1;
357 # aggregate null and empty values under empty value
358 push @criteria_dv, '' if $criteria_has_empty;
360 # Hack to not modify GetDistinctValues for this specific case
361 if ( $displayby eq 'branchcode'
362 && C4::Context->preference('IndependentBranches')
363 && not C4::Context->IsSuperLibrarian )
365 @criteria_dv = ( C4::Context->userenv->{'branch'} );
368 if ( $displayby eq 'STATUS' ) {
369 @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv;
370 unshift @criteria_dv, 'ASKED';
373 unless ( exists $suggestion_ref->{branchcode} ) {
374 $suggestion_ref->{branchcode} = C4::Context->userenv->{'branch'};
378 foreach my $criteriumvalue ( @criteria_dv ) {
379 my $search_params = {%$suggestion_ref};
382 if $search_params->{STATUS}
383 && $displayby eq 'STATUS'
384 && $criteriumvalue ne $search_params->{STATUS};
386 # By default, display suggestions from current working branch
387 my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
389 next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
391 $search_params->{$displayby} = $criteriumvalue;
393 # filter on date fields
394 foreach my $field (qw( suggesteddate manageddate accepteddate )) {
395 my $from = delete $search_params->{"${field}_from"};
396 my $to = delete $search_params->{"${field}_to"};
398 my $from_dt = $from && eval { dt_from_string($from) };
399 my $to_dt = $to && eval { dt_from_string($to) };
401 if ( $from_dt || $to_dt ) {
402 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
403 if ( $from_dt && $to_dt ) {
404 $search_params->{$field} = { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] };
405 } elsif ( $from_dt ) {
406 $search_params->{$field} = { '>=' => $dtf->format_date($from_dt) };
408 $search_params->{$field} = { '<=' => $dtf->format_date($to_dt) };
412 if ( $search_params->{budgetid} && $search_params->{budgetid} eq '__NONE__' ) {
413 $search_params->{budgetid} = [undef, '' ];
415 for my $f (qw (branchcode budgetid)) {
416 delete $search_params->{$f}
417 if $search_params->{$f} eq '__ANY__'
418 || $search_params->{$f} eq '';
420 for my $bi (qw (title author isbn publishercode copyrightdate collectiontitle)) {
421 $search_params->{$bi} = { 'LIKE' => "%" . $search_params->{$bi} . "%" } if $search_params->{$bi};
424 $search_params->{archived} = 0 if !$filter_archived;
425 my @suggestions = Koha::Suggestions->search_limited($search_params)->as_list;
427 push @allsuggestions,
429 "suggestiontype" => $criteriumvalue || "suggest",
430 "suggestiontypelabel" => GetCriteriumDesc( $criteriumvalue, $displayby ) || "",
431 'suggestions' => \@suggestions,
432 'reasonsloop' => $reasonsloop,
434 if scalar @suggestions > 0;
436 delete $$suggestion_ref{$displayby} unless $definedvalue;
440 "displayby"=> $displayby,
441 "notabs"=> $displayby eq "",
442 suggestions => \@allsuggestions,
447 "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
448 for qw(managedby suggestedby acceptedby lastmodificationby);
452 filter_archived => $filter_archived,
456 if(defined($returnsuggested) and $returnsuggested ne "noone")
458 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
462 branchfilter => $branchfilter,
465 $template->param( returnsuggestedby => $returnsuggestedby );
467 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
468 $template->param(patron_reason_loop=>$patron_reason_loop);
470 # Budgets for filtering
471 my $budgets = GetBudgets;
473 foreach my $budget ( @{$budgets} ) {
474 next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
476 ## Please see file perltidy.ERR
477 $budget->{'selected'} = 1
478 if ($$suggestion_ref{'budgetid'}
479 && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
481 push @budgets_loop, $budget;
483 $template->param( budgetsloop => \@budgets_loop);
485 # Budgets for suggestion add or edition
486 my $sugg_budget_loop = [];
487 my $sugg_budgets = GetBudgetHierarchy();
488 foreach my $r ( @{$sugg_budgets} ) {
489 next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
490 my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
491 push @{$sugg_budget_loop},
493 b_id => $r->{budget_id},
494 b_txt => $r->{budget_name},
495 b_active => $r->{budget_period_active},
496 selected => $selected,
499 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
500 $template->param( sugg_budgets => $sugg_budget_loop);
502 if( $suggestion_ref->{STATUS} ) {
504 "statusselected_".$suggestion_ref->{STATUS} => 1,
505 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
509 my $currencies = Koha::Acquisition::Currencies->search;
511 currencies => $currencies,
512 suggestion => $suggestion_ref,
513 price => sprintf("%.2f", $$suggestion_ref{'price'}||0),
514 total => sprintf("%.2f", $$suggestion_ref{'total'}||0),
517 # lists of distinct values (without empty) for filters
519 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
521 $values_list = GetDistinctValues( "suggestions." . $field );
522 my @codes_list = map {
523 { 'code' => $$_{'value'},
524 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
525 'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
530 @codes_list = sort { $a->{desc} cmp $b->{desc} } @codes_list;
531 $hashlists{ lc($field) . "_loop" } = \@codes_list;
536 borrowernumber => ( $input->param('borrowernumber') // undef ),
537 SuggestionStatuses => GetAuthorisedValues('SUGGEST_STATUS'),
540 output_html_with_http_headers $input, $cookie, $template->output;
542 sub redirect_with_params {
547 displayby branchcode title author isbn publishercode copyrightdate
548 collectiontitle suggestedby suggesteddate_from suggesteddate_to
549 manageddate_from manageddate_to accepteddate_from
550 accepteddate_to budgetid filter_archived
554 $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
555 if defined($input->param($key));
557 print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");