Bug 19918: Close span tag in opac-registration-confirmation.tt
[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 strict;
21 #use warnings; FIXME - Bug 2505
22 require Exporter;
23 use CGI qw ( -utf8 );
24 use C4::Auth;    # get_template_and_user
25 use C4::Output;
26 use C4::Suggestions;
27 use C4::Koha;
28 use C4::Budgets;
29 use C4::Search;
30 use C4::Members;
31 use C4::Debug;
32
33 use Koha::DateUtils qw( dt_from_string );
34 use Koha::AuthorisedValues;
35 use Koha::Acquisition::Currencies;
36 use Koha::Libraries;
37 use Koha::Patrons;
38
39 use URI::Escape;
40
41 sub Init{
42     my $suggestion= shift @_;
43     # "Managed by" is used only when a suggestion is being edited (not when created)
44     if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
45         # new suggestion
46         $suggestion->{suggesteddate} = dt_from_string;
47         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
48     }
49     else {
50         # editing of an existing suggestion
51         $suggestion->{manageddate} = dt_from_string;
52         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
53     }
54     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
55 }
56
57 sub GetCriteriumDesc{
58     my ($criteriumvalue,$displayby)=@_;
59     if ($displayby =~ /status/i) {
60         unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
61             my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
62             return $av->count ? $av->next->lib : 'Unknown';
63         }
64         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
65     }
66     return Koha::Libraries->find($criteriumvalue)->branchname
67         if $displayby =~ /branchcode/;
68     if ( $displayby =~ /itemtype/ ) {
69         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
70         return $av->count ? $av->next->lib : 'Unknown';
71     }
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;
76     }
77     if ( $displayby =~ /budgetid/) {
78         my $budget = GetBudget($criteriumvalue);
79         return "" unless $budget;
80         return $$budget{budget_name};
81     }
82 }
83
84 my $input           = CGI->new;
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('edit_field');
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 $reasonsloop     = GetAuthorisedValues("SUGGEST");
96
97 # filter informations which are not suggestion related.
98 my $suggestion_ref  = $input->Vars;
99
100 # get only the columns of Suggestion
101 my $schema = Koha::Database->new()->schema;
102 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
103 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
104 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
105
106 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field );
107 foreach (keys %$suggestion_ref){
108     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' || $op eq 'change'));
109 }
110 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
111         {
112             template_name   => "suggestion/suggestion.tt",
113             query           => $input,
114             type            => "intranet",
115             flagsrequired   => { catalogue => 1 },
116         }
117     );
118
119 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
120 $template->param('borrowernumber' => $borrowernumber);
121
122 #########################################
123 ##  Operations
124 ##
125 if ( $op =~ /save/i ) {
126     $suggestion_only->{suggesteddate} = dt_from_string( $suggestion_only->{suggesteddate} )
127         if $suggestion_only->{suggesteddate};
128
129     if ( $suggestion_only->{"STATUS"} ) {
130         if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
131             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
132             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
133         }
134         $suggestion_only->{manageddate} = dt_from_string;
135         $suggestion_only->{"managedby"}   = C4::Context->userenv->{number};
136     }
137
138     my $otherreason = $input->param('other_reason');
139     if ($suggestion_only->{reason} eq 'other' && $otherreason) {
140         $suggestion_only->{reason} = $otherreason;
141     }
142
143     if ( $suggestion_only->{'suggestionid'} > 0 ) {
144         &ModSuggestion($suggestion_only);
145     } else {
146         ###FIXME:Search here if suggestion already exists.
147         my $suggestions_loop =
148             SearchSuggestion( $suggestion_only );
149         if (@$suggestions_loop>=1){
150             #some suggestion are answering the request Donot Add
151             my @messages;
152             for my $suggestion ( @$suggestions_loop ) {
153                 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
154             }
155             $template->param( messages => \@messages );
156         } 
157         else {    
158             ## Adding some informations related to suggestion
159             &NewSuggestion($suggestion_only);
160         }
161         # empty fields, to avoid filter in "SearchSuggestion"
162     }  
163     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
164     $op = 'else';
165
166     if( $redirect eq 'purchase_suggestions' ) {
167         print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
168     }
169
170 }
171 elsif ($op=~/add/) {
172     #Adds suggestion  
173     Init($suggestion_ref);
174     $op ='save';
175
176 elsif ($op=~/edit/) {
177     #Edit suggestion  
178     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
179     $suggestion_ref->{reasonsloop} = $reasonsloop;
180     my $other_reason = 1;
181     foreach my $reason ( @{ $reasonsloop } ) {
182         if ($suggestion_ref->{reason} eq $reason->{lib}) {
183             $other_reason = 0;
184         }
185     }
186     $other_reason = 0 unless $suggestion_ref->{reason};
187     $template->param(other_reason => $other_reason);
188     Init($suggestion_ref);
189     $op ='save';
190 }  
191 elsif ($op eq "change" ) {
192     # set accepted/rejected/managed informations if applicable
193     # ie= if the librarian has chosen some action on the suggestions
194     if ($suggestion_only->{"STATUS"} eq "ACCEPTED"){
195         $suggestion_only->{accepteddate} = dt_from_string;
196         $suggestion_only->{"acceptedby"}=C4::Context->userenv->{number};
197     } elsif ($suggestion_only->{"STATUS"} eq "REJECTED"){
198         $suggestion_only->{rejecteddate} = dt_from_string;
199         $suggestion_only->{"rejectedby"}=C4::Context->userenv->{number};
200     }
201     if ($suggestion_only->{"STATUS"}){
202         $suggestion_only->{manageddate} = dt_from_string;
203         $suggestion_only->{"managedby"}=C4::Context->userenv->{number};
204     }
205     if ( my $reason = $$suggestion_ref{"reason$tabcode"}){
206         if ( $reason eq "other" ) {
207             $reason = $$suggestion_ref{"other_reason$tabcode"};
208         }
209         $suggestion_only->{reason}=$reason;
210     }
211
212     foreach my $suggestionid (@editsuggestions) {
213         next unless $suggestionid;
214         $suggestion_only->{'suggestionid'}=$suggestionid;
215         &ModSuggestion($suggestion_only);
216     }
217     my $params = '';
218     foreach my $key (
219         qw(
220         displayby branchcode title author isbn publishercode copyrightdate
221         collectiontitle suggestedby suggesteddate_from suggesteddate_to
222         manageddate_from manageddate_to accepteddate_from
223         accepteddate_to budgetid
224         )
225       )
226     {
227         $params .= $key . '=' . uri_escape($input->param($key)) . '&'
228           if defined($input->param($key));
229     }
230     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
231 }elsif ($op eq "delete" ) {
232     foreach my $delete_field (@editsuggestions) {
233         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
234     }
235     $op = 'else';
236 }
237 elsif ( $op eq 'show' ) {
238     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
239     my $budget = GetBudget $$suggestion_ref{budgetid};
240     $$suggestion_ref{budgetname} = $$budget{budget_name};
241     Init($suggestion_ref);
242 }
243 if ($op=~/else/) {
244     $op='else';
245     
246     $displayby||="STATUS";
247     delete $$suggestion_ref{'branchcode'} if($displayby eq "branchcode");
248     # distinct values of display by
249     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
250     my (@criteria_dv, $criteria_has_empty);
251     foreach (@$criteria_list) {
252         if ($_->{value}) {
253             push @criteria_dv, $_->{value};
254         } else {
255             $criteria_has_empty = 1;
256         }
257     }
258     # aggregate null and empty values under empty value
259     push @criteria_dv, '' if $criteria_has_empty;
260
261     my @allsuggestions;
262     foreach my $criteriumvalue ( @criteria_dv ) {
263         # By default, display suggestions from current working branch
264         unless ( exists $$suggestion_ref{'branchcode'} ) {
265             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
266         }
267         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
268
269         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue );
270         $$suggestion_ref{$displayby} = $criteriumvalue;
271
272         my $suggestions = &SearchSuggestion($suggestion_ref);
273         foreach my $suggestion (@$suggestions) {
274             if ($suggestion->{budgetid}){
275                 my $bud = GetBudget( $suggestion->{budgetid} );
276                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
277             }
278         }
279         push @allsuggestions,{
280                             "suggestiontype"=>$criteriumvalue||"suggest",
281                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
282                             "suggestionscount"=>scalar(@$suggestions),             
283                             'suggestions_loop'=>$suggestions,
284                             'reasonsloop'     => $reasonsloop,
285                             };
286
287         delete $$suggestion_ref{$displayby} unless $definedvalue;
288     }
289
290     $template->param(
291         "displayby"=> $displayby,
292         "notabs"=> $displayby eq "",
293         suggestions       => \@allsuggestions,
294     );
295 }
296
297 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
298 #    $debug || warn $$suggestion_ref{$element};
299     if ($$suggestion_ref{$element}){
300         my $patron = Koha::Patrons->find( $$suggestion_ref{$element} );
301         my $category = $patron->category;
302         $template->param(
303             $element."_borrowernumber"=>$patron->borrowernumber,
304             $element."_firstname"=>$patron->firstname,
305             $element."_surname"=>$patron->surname,
306             $element."_cardnumber"=>$patron->cardnumber,
307             $element."_branchcode"=>$patron->branchcode,
308             $element."_description"=>$category->description,
309             $element."_category_type"=>$category->category_type,
310         );
311     }
312 }
313 $template->param(
314     %$suggestion_ref,  
315     "op_$op"                => 1,
316     "op"             =>$op,
317 );
318
319 if(defined($returnsuggested) and $returnsuggested ne "noone")
320 {
321     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
322 }
323
324 my $branchfilter = ($displayby ne "branchcode") ? $input->param('branchcode') : C4::Context->userenv->{'branch'};
325
326 $template->param(
327     branchfilter => $branchfilter,
328 );
329
330 $template->param( returnsuggestedby => $returnsuggestedby );
331
332 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
333 $template->param(patron_reason_loop=>$patron_reason_loop);
334
335 #Budgets management
336 my $budgets = [];
337 if ($branchfilter) {
338     my $searchbudgets = { budget_branchcode => $branchfilter };
339     $budgets = GetBudgets($searchbudgets);
340 } else {
341     $budgets = GetBudgets(undef);
342 }
343
344 my @budgets_loop;
345 foreach my $budget ( @{$budgets} ) {
346     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
347
348     ## Please see file perltidy.ERR
349     $budget->{'selected'} = 1
350         if ($$suggestion_ref{'budgetid'}
351         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
352
353     push @budgets_loop, $budget;
354 }
355
356 $template->param( budgetsloop => \@budgets_loop);
357 $template->param( "statusselected_$$suggestion_ref{'STATUS'}" =>1) if ($$suggestion_ref{'STATUS'});
358
359 my @currencies = Koha::Acquisition::Currencies->search;
360 $template->param(
361     currencies   => \@currencies,
362     suggestion   => $suggestion_ref,
363     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
364     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
365 );
366
367 # lists of distinct values (without empty) for filters
368 my %hashlists;
369 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
370     my $values_list;
371     $values_list = GetDistinctValues( "suggestions." . $field );
372     my @codes_list = map {
373         {   'code' => $$_{'value'},
374             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
375             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
376         }
377     } grep {
378         $$_{'value'}
379     } @$values_list;
380     $hashlists{ lc($field) . "_loop" } = \@codes_list;
381 }
382
383 $template->param(
384     %hashlists,
385     borrowernumber           => ($input->param('borrowernumber') // undef),
386     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
387 );
388 output_html_with_http_headers $input, $cookie, $template->output;