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