Bug 23590: Add the ability to notify a new manager
[koha.git] / suggestion / suggestion.pl
blob1dad30a2f749c01cdc79fbffb00ba2ac962b970e
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 return Koha::Libraries->find($criteriumvalue)->branchname
65 if $displayby =~ /branchcode/;
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};
82 my $input = CGI->new;
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');
96 my $reasonsloop = GetAuthorisedValues("SUGGEST");
98 # filter informations which are not suggestion related.
99 my $suggestion_ref = $input->Vars;
101 # get only the columns of Suggestion
102 my $schema = Koha::Database->new()->schema;
103 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
104 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
105 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
107 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field notify );
108 foreach (keys %$suggestion_ref){
109 delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
111 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
113 template_name => "suggestion/suggestion.tt",
114 query => $input,
115 type => "intranet",
116 flagsrequired => { suggestions => 'suggestions_manage' },
120 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
121 $template->param('borrowernumber' => $borrowernumber);
122 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
124 #########################################
125 ## Operations
128 if ( $op =~ /save/i ) {
129 my @messages;
130 my $biblio = MarcRecordFromNewSuggestion({
131 title => $suggestion_only->{title},
132 author => $suggestion_only->{author},
133 itemtype => $suggestion_only->{itemtype},
136 if ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
137 push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
138 $template->param(
139 messages => \@messages,
140 need_confirm => 1
142 delete $suggestion_ref->{suggesteddate};
143 Init($suggestion_ref);
145 else {
147 for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
148 $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
149 if $suggestion_only->{$date_key};
152 if ( $suggestion_only->{"STATUS"} ) {
153 if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
154 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
155 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" } = C4::Context->userenv->{number};
157 $suggestion_only->{manageddate} = dt_from_string;
158 $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
161 my $otherreason = $input->param('other_reason');
162 if ($suggestion_only->{reason} eq 'other' && $otherreason) {
163 $suggestion_only->{reason} = $otherreason;
166 if ( $suggestion_only->{'suggestionid'} > 0 ) {
168 &ModSuggestion($suggestion_only);
170 if ( $notify ) {
171 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
172 my $email_address = $patron->notice_email_address;
173 if ($patron->notice_email_address) {
174 my $budget = C4::Budgets::GetBudget( $suggestion_only->{budgetid} );
175 my $library = $patron->library;
176 my $admin_email_address = $library->branchemail
177 || C4::Context->preference('KohaAdminEmailAddress');
179 my $letter = C4::Letters::GetPreparedLetter(
180 module => 'suggestions',
181 letter_code => 'TO_PROCESS',
182 branchcode => $patron->branchcode,
183 lang => $patron->lang,
184 tables => {
185 suggestions => $suggestion_only->{suggestionid},
186 branches => $patron->branchcode,
187 borrowers => $patron->borrowernumber,
190 C4::Letters::EnqueueLetter(
192 letter => $letter,
193 borrowernumber => $patron->borrowernumber,
194 message_transport_type => 'email',
195 from_address => $admin_email_address,
200 } else {
201 ###FIXME:Search here if suggestion already exists.
202 my $suggestions_loop =
203 SearchSuggestion( $suggestion_only );
204 if (@$suggestions_loop>=1){
205 #some suggestion are answering the request Donot Add
206 my @messages;
207 for my $suggestion ( @$suggestions_loop ) {
208 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
210 $template->param( messages => \@messages );
212 else {
213 ## Adding some informations related to suggestion
214 &NewSuggestion($suggestion_only);
216 # empty fields, to avoid filter in "SearchSuggestion"
218 map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
219 $op = 'else';
221 if( $redirect eq 'purchase_suggestions' ) {
222 print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
226 elsif ($op=~/add/) {
227 #Adds suggestion
228 Init($suggestion_ref);
229 $op ='save';
231 elsif ($op=~/edit/) {
232 #Edit suggestion
233 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
234 $suggestion_ref->{reasonsloop} = $reasonsloop;
235 my $other_reason = 1;
236 foreach my $reason ( @{ $reasonsloop } ) {
237 if ($suggestion_ref->{reason} eq $reason->{lib}) {
238 $other_reason = 0;
241 $other_reason = 0 unless $suggestion_ref->{reason};
242 $template->param(other_reason => $other_reason);
243 Init($suggestion_ref);
244 $op ='save';
246 elsif ($op eq "update_status" ) {
248 my $suggestion;
249 # set accepted/rejected/managed informations if applicable
250 # ie= if the librarian has chosen some action on the suggestions
251 my $STATUS = $input->param('STATUS');
252 my $accepted_by = $input->param('acceptedby');
253 if ( $STATUS eq "ACCEPTED" ) {
254 $suggestion = {
255 accepteddate => dt_from_string,
256 acceptedby => C4::Context->userenv->{number},
259 elsif ( $STATUS eq "REJECTED" ) {
260 $suggestion = {
261 rejecteddate => dt_from_string,
262 rejectedby => C4::Context->userenv->{number},
265 if ($STATUS) {
266 $suggestion->{manageddate} = dt_from_string;
267 $suggestion->{managedby} = C4::Context->userenv->{number};
268 $suggestion->{STATUS} = $STATUS;
270 if ( my $reason = $input->param("reason") ) {
271 if ( $reason eq "other" ) {
272 $reason = $input->param("other_reason");
274 $suggestion->{reason} = $reason;
277 foreach my $suggestionid (@editsuggestions) {
278 next unless $suggestionid;
279 $suggestion->{suggestionid} = $suggestionid;
280 &ModSuggestion($suggestion);
282 redirect_with_params($input);
283 }elsif ($op eq "delete" ) {
284 foreach my $delete_field (@editsuggestions) {
285 &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
287 redirect_with_params($input);
289 elsif ( $op eq 'update_itemtype' ) {
290 my $new_itemtype = $input->param('suggestion_itemtype');
291 foreach my $suggestionid (@editsuggestions) {
292 next unless $suggestionid;
293 &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
295 redirect_with_params($input);
297 elsif ( $op eq 'update_manager' ) {
298 my $managedby = $input->param('suggestion_managedby');
299 foreach my $suggestionid (@editsuggestions) {
300 next unless $suggestionid;
301 &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
303 redirect_with_params($input);
305 elsif ( $op eq 'show' ) {
306 $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
307 my $budget = GetBudget $$suggestion_ref{budgetid};
308 $$suggestion_ref{budgetname} = $$budget{budget_name};
309 Init($suggestion_ref);
311 if ($op=~/else/) {
312 $op='else';
314 $displayby||="STATUS";
315 # distinct values of display by
316 my $criteria_list=GetDistinctValues("suggestions.".$displayby);
317 my (@criteria_dv, $criteria_has_empty);
318 foreach (@$criteria_list) {
319 if ($_->{value}) {
320 push @criteria_dv, $_->{value};
321 } else {
322 $criteria_has_empty = 1;
325 # aggregate null and empty values under empty value
326 push @criteria_dv, '' if $criteria_has_empty;
328 # Hack to not modify GetDistinctValues for this specific case
329 if ( $displayby eq 'branchcode'
330 && C4::Context->preference('IndependentBranches')
331 && not C4::Context->IsSuperLibrarian )
333 @criteria_dv = ( C4::Context->userenv->{'branch'} );
336 my @allsuggestions;
337 foreach my $criteriumvalue ( @criteria_dv ) {
338 # By default, display suggestions from current working branch
339 unless ( exists $$suggestion_ref{'branchcode'} ) {
340 $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
342 my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
344 next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' or $branchfilter ne '__ANY__' );
345 $$suggestion_ref{$displayby} = $criteriumvalue;
347 my $suggestions = &SearchSuggestion($suggestion_ref);
348 foreach my $suggestion (@$suggestions) {
349 if ($suggestion->{budgetid}){
350 my $bud = GetBudget( $suggestion->{budgetid} );
351 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
354 push @allsuggestions,{
355 "suggestiontype"=>$criteriumvalue||"suggest",
356 "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
357 "suggestionscount"=>scalar(@$suggestions),
358 'suggestions_loop'=>$suggestions,
359 'reasonsloop' => $reasonsloop,
362 delete $$suggestion_ref{$displayby} unless $definedvalue;
365 $template->param(
366 "displayby"=> $displayby,
367 "notabs"=> $displayby eq "",
368 suggestions => \@allsuggestions,
372 $template->param(
373 "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
374 for qw(managedby suggestedby acceptedby);
376 $template->param(
377 %$suggestion_ref,
378 "op" =>$op,
381 if(defined($returnsuggested) and $returnsuggested ne "noone")
383 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
386 $template->param(
387 branchfilter => $branchfilter,
390 $template->param( returnsuggestedby => $returnsuggestedby );
392 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
393 $template->param(patron_reason_loop=>$patron_reason_loop);
395 #Budgets management
396 my $budgets = GetBudgets;
397 my @budgets_loop;
398 foreach my $budget ( @{$budgets} ) {
399 next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
401 ## Please see file perltidy.ERR
402 $budget->{'selected'} = 1
403 if ($$suggestion_ref{'budgetid'}
404 && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
406 push @budgets_loop, $budget;
409 $template->param( budgetsloop => \@budgets_loop);
410 if( $suggestion_ref->{STATUS} ) {
411 $template->param(
412 "statusselected_".$suggestion_ref->{STATUS} => 1,
413 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
417 my @currencies = Koha::Acquisition::Currencies->search;
418 $template->param(
419 currencies => \@currencies,
420 suggestion => $suggestion_ref,
421 price => sprintf("%.2f", $$suggestion_ref{'price'}||0),
422 total => sprintf("%.2f", $$suggestion_ref{'total'}||0),
425 # lists of distinct values (without empty) for filters
426 my %hashlists;
427 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
428 my $values_list;
429 $values_list = GetDistinctValues( "suggestions." . $field );
430 my @codes_list = map {
431 { 'code' => $$_{'value'},
432 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
433 'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
435 } grep {
436 $$_{'value'}
437 } @$values_list;
438 $hashlists{ lc($field) . "_loop" } = \@codes_list;
441 $template->param(
442 %hashlists,
443 borrowernumber => ($input->param('borrowernumber') // undef),
444 SuggestionStatuses => GetAuthorisedValues('SUGGEST_STATUS'),
446 output_html_with_http_headers $input, $cookie, $template->output;
448 sub redirect_with_params {
449 my ( $input ) = @_;
450 my $params = '';
451 foreach my $key (
453 displayby branchcode title author isbn publishercode copyrightdate
454 collectiontitle suggestedby suggesteddate_from suggesteddate_to
455 manageddate_from manageddate_to accepteddate_from
456 accepteddate_to budgetid
460 $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
461 if defined($input->param($key));
463 print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");