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