Bug 27495: Added Accessibility advocate role in team page
[koha.git] / suggestion / suggestion.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 # Copyright 2006-2010 BibLibre
5
6 #
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.
11 #
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.
16 #
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>.
19
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;
36
37 use URI::Escape;
38
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 "") {
43         # new suggestion
44         $suggestion->{suggesteddate} = dt_from_string;
45         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
46     }
47     else {
48         # editing of an existing suggestion
49         $suggestion->{manageddate} = dt_from_string;
50         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
51     }
52     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
53 }
54
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';
61         }
62         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
63     }
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';
69     }
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;
74     }
75     if ( $displayby =~ /budgetid/) {
76         my $budget = GetBudget($criteriumvalue);
77         return "" unless $budget;
78         return $$budget{budget_name};
79     }
80 }
81
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');
95 my $filter_archived = $input->param('filter_archived');
96
97 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
98
99 # filter informations which are not suggestion related.
100 my $suggestion_ref  = { %{$input->Vars} }; # Copying, otherwise $input will be modified
101
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};
107
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' ));
111 }
112 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
113         {
114             template_name   => "suggestion/suggestion.tt",
115             query           => $input,
116             type            => "intranet",
117             flagsrequired   => { suggestions => 'suggestions_manage' },
118         }
119     );
120
121 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
122 $template->param('borrowernumber' => $borrowernumber);
123 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
124
125 #########################################
126 ##  Operations
127 ##
128
129 if ( $op =~ /save/i ) {
130     my @messages;
131     my $biblio = MarcRecordFromNewSuggestion({
132             title => $suggestion_only->{title},
133             author => $suggestion_only->{author},
134             itemtype => $suggestion_only->{itemtype},
135     });
136
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' };
140         $template->param(
141             messages => \@messages,
142         );
143         delete $suggestion_ref->{suggesteddate};
144         delete $suggestion_ref->{manageddate};
145         delete $suggestion_ref->{managedby};
146         Init($suggestion_ref);
147     }
148     elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
149         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
150         $template->param(
151             messages => \@messages,
152             need_confirm => 1
153         );
154         delete $suggestion_ref->{suggesteddate};
155         delete $suggestion_ref->{manageddate};
156         Init($suggestion_ref);
157     }
158     else {
159
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};
163         }
164
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};
169             }
170             $suggestion_only->{manageddate} = dt_from_string;
171             $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
172         }
173
174         my $otherreason = $input->param('other_reason');
175         if ($suggestion_only->{reason} eq 'other' && $otherreason) {
176             $suggestion_only->{reason} = $otherreason;
177         }
178
179         if ( $suggestion_only->{'suggestionid'} > 0 ) {
180
181             $suggestion_only->{lastmodificationdate} = dt_from_string;
182             $suggestion_only->{lastmodificationby}   = C4::Context->userenv->{number};
183
184             &ModSuggestion($suggestion_only);
185
186             if ( $notify ) {
187                 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
188                 my $email_address = $patron->notice_email_address;
189                 if ($patron->notice_email_address) {
190                     my $library = $patron->library;
191                     my $admin_email_address = $library->branchemail
192                       || C4::Context->preference('KohaAdminEmailAddress');
193
194                     my $letter = C4::Letters::GetPreparedLetter(
195                         module      => 'suggestions',
196                         letter_code => 'NOTIFY_MANAGER',
197                         branchcode  => $patron->branchcode,
198                         lang        => $patron->lang,
199                         tables      => {
200                             suggestions => $suggestion_only->{suggestionid},
201                             branches    => $patron->branchcode,
202                             borrowers   => $patron->borrowernumber,
203                         },
204                     );
205                     C4::Letters::EnqueueLetter(
206                         {
207                             letter                 => $letter,
208                             borrowernumber         => $patron->borrowernumber,
209                             message_transport_type => 'email',
210                             from_address           => $admin_email_address,
211                         }
212                     );
213                 }
214             }
215         } else {
216             ###FIXME:Search here if suggestion already exists.
217             my $suggestions_loop =
218                 SearchSuggestion( $suggestion_only );
219             if (@$suggestions_loop>=1){
220                 #some suggestion are answering the request Donot Add
221                 my @messages;
222                 for my $suggestion ( @$suggestions_loop ) {
223                     push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
224                 }
225                 $template->param( messages => \@messages );
226             }
227             else {
228                 ## Adding some informations related to suggestion
229                 &NewSuggestion($suggestion_only);
230             }
231             # empty fields, to avoid filter in "SearchSuggestion"
232         }
233         map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
234         $op = 'else';
235
236         if( $redirect eq 'purchase_suggestions' ) {
237             print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
238         }
239     }
240 }
241 elsif ($op=~/add/) {
242     #Adds suggestion
243     Init($suggestion_ref);
244     $op ='save';
245 }
246 elsif ($op=~/edit/) {
247     #Edit suggestion  
248     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
249     $suggestion_ref->{reasonsloop} = $reasonsloop;
250     my $other_reason = 1;
251     foreach my $reason ( @{ $reasonsloop } ) {
252         if ($suggestion_ref->{reason} eq $reason->{lib}) {
253             $other_reason = 0;
254         }
255     }
256     $other_reason = 0 unless $suggestion_ref->{reason};
257     $template->param(other_reason => $other_reason);
258     Init($suggestion_ref);
259     $op ='save';
260 }  
261 elsif ($op eq "update_status" ) {
262
263     my $suggestion;
264     # set accepted/rejected/managed informations if applicable
265     # ie= if the librarian has chosen some action on the suggestions
266     my $STATUS      = $input->param('STATUS');
267     my $accepted_by = $input->param('acceptedby');
268     if ( $STATUS eq "ACCEPTED" ) {
269         $suggestion = {
270             accepteddate => dt_from_string,
271             acceptedby => C4::Context->userenv->{number},
272         };
273     }
274     elsif ( $STATUS eq "REJECTED" ) {
275         $suggestion = {
276             rejecteddate => dt_from_string,
277             rejectedby   => C4::Context->userenv->{number},
278         };
279     }
280     if ($STATUS) {
281         $suggestion->{manageddate} = dt_from_string;
282         $suggestion->{managedby}   = C4::Context->userenv->{number};
283         $suggestion->{STATUS}      = $STATUS;
284     }
285     if ( my $reason = $input->param("reason") ) {
286         if ( $reason eq "other" ) {
287             $reason = $input->param("other_reason");
288         }
289         $suggestion->{reason} = $reason;
290     }
291
292     foreach my $suggestionid (@editsuggestions) {
293         next unless $suggestionid;
294         $suggestion->{suggestionid} = $suggestionid;
295         &ModSuggestion($suggestion);
296     }
297     redirect_with_params($input);
298 }elsif ($op eq "delete" ) {
299     foreach my $delete_field (@editsuggestions) {
300         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
301     }
302     redirect_with_params($input);
303 }
304 elsif ($op eq "archive" ) {
305     Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
306
307     redirect_with_params($input);
308 }
309 elsif ($op eq "unarchive" ) {
310     Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
311
312     redirect_with_params($input);
313 }
314 elsif ( $op eq 'update_itemtype' ) {
315     my $new_itemtype = $input->param('suggestion_itemtype');
316     foreach my $suggestionid (@editsuggestions) {
317         next unless $suggestionid;
318         &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
319     }
320     redirect_with_params($input);
321 }
322 elsif ( $op eq 'update_manager' ) {
323     my $managedby = $input->param('suggestion_managedby');
324     foreach my $suggestionid (@editsuggestions) {
325         next unless $suggestionid;
326         &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
327     }
328     redirect_with_params($input);
329 }
330 elsif ( $op eq 'show' ) {
331     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
332     my $budget = GetBudget $$suggestion_ref{budgetid};
333     $$suggestion_ref{budgetname} = $$budget{budget_name};
334     Init($suggestion_ref);
335 }
336 if ($op=~/else/) {
337     $op='else';
338     
339     $displayby||="STATUS";
340     # distinct values of display by
341     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
342     my (@criteria_dv, $criteria_has_empty);
343     foreach (@$criteria_list) {
344         if ($_->{value}) {
345             push @criteria_dv, $_->{value};
346         } else {
347             $criteria_has_empty = 1;
348         }
349     }
350     # aggregate null and empty values under empty value
351     push @criteria_dv, '' if $criteria_has_empty;
352
353     # Hack to not modify GetDistinctValues for this specific case
354     if (   $displayby eq 'branchcode'
355         && C4::Context->preference('IndependentBranches')
356         && not C4::Context->IsSuperLibrarian )
357     {
358         @criteria_dv = ( C4::Context->userenv->{'branch'} );
359     }
360
361     my @allsuggestions;
362     foreach my $criteriumvalue ( @criteria_dv ) {
363         # By default, display suggestions from current working branch
364         unless ( exists $$suggestion_ref{'branchcode'} ) {
365             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
366         }
367         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
368
369         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' or $branchfilter ne '__ANY__' );
370         $$suggestion_ref{$displayby} = $criteriumvalue;
371
372         my $suggestions = &SearchSuggestion({ %$suggestion_ref, archived => $filter_archived });
373         foreach my $suggestion (@$suggestions) {
374             if ($suggestion->{budgetid}){
375                 my $bud = GetBudget( $suggestion->{budgetid} );
376                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
377             }
378         }
379         push @allsuggestions,{
380                             "suggestiontype"=>$criteriumvalue||"suggest",
381                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
382                             "suggestionscount"=>scalar(@$suggestions),             
383                             'suggestions_loop'=>$suggestions,
384                             'reasonsloop'     => $reasonsloop,
385                             } if @$suggestions;
386
387         delete $$suggestion_ref{$displayby} unless $definedvalue;
388     }
389
390     $template->param(
391         "displayby"=> $displayby,
392         "notabs"=> $displayby eq "",
393         suggestions       => \@allsuggestions,
394     );
395 }
396
397 $template->param(
398     "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
399   for qw(managedby suggestedby acceptedby lastmodificationby);
400
401 $template->param(
402     %$suggestion_ref,
403     filter_archived => $filter_archived,
404     "op"             =>$op,
405 );
406
407 if(defined($returnsuggested) and $returnsuggested ne "noone")
408 {
409     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
410 }
411
412 $template->param(
413     branchfilter => $branchfilter,
414 );
415
416 $template->param( returnsuggestedby => $returnsuggestedby );
417
418 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
419 $template->param(patron_reason_loop=>$patron_reason_loop);
420
421 #Budgets management
422 my $budgets = GetBudgets;
423 my @budgets_loop;
424 foreach my $budget ( @{$budgets} ) {
425     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
426
427     ## Please see file perltidy.ERR
428     $budget->{'selected'} = 1
429         if ($$suggestion_ref{'budgetid'}
430         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
431
432     push @budgets_loop, $budget;
433 }
434
435 $template->param( budgetsloop => \@budgets_loop);
436 if( $suggestion_ref->{STATUS} ) {
437     $template->param(
438         "statusselected_".$suggestion_ref->{STATUS} => 1,
439         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
440     );
441 }
442
443 my @currencies = Koha::Acquisition::Currencies->search;
444 $template->param(
445     currencies   => \@currencies,
446     suggestion   => $suggestion_ref,
447     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
448     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
449 );
450
451 # lists of distinct values (without empty) for filters
452 my %hashlists;
453 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
454     my $values_list;
455     $values_list = GetDistinctValues( "suggestions." . $field );
456     my @codes_list = map {
457         {   'code' => $$_{'value'},
458             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
459             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
460         }
461     } grep {
462         $$_{'value'}
463     } @$values_list;
464     $hashlists{ lc($field) . "_loop" } = \@codes_list;
465 }
466
467 $template->param(
468     %hashlists,
469     borrowernumber           => ($input->param('borrowernumber') // undef),
470     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
471 );
472 output_html_with_http_headers $input, $cookie, $template->output;
473
474 sub redirect_with_params {
475     my ( $input ) = @_;
476     my $params = '';
477     foreach my $key (
478         qw(
479         displayby branchcode title author isbn publishercode copyrightdate
480         collectiontitle suggestedby suggesteddate_from suggesteddate_to
481         manageddate_from manageddate_to accepteddate_from
482         accepteddate_to budgetid filter_archived
483         )
484       )
485     {
486         $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
487           if defined($input->param($key));
488     }
489     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
490 }