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