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