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