Bug 8435: DBRev 3.13.00.038
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 require Exporter;
23 use CGI;
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::Dates qw(format_date);
32 use C4::Members;
33 use C4::Debug;
34
35 sub Init{
36     my $suggestion= shift @_;
37     # "Managed by" is used only when a suggestion is being edited (not when created)
38     if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
39         # new suggestion
40         $suggestion->{'suggesteddate'} = C4::Dates->today;
41         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
42     }
43     else {
44         # editing of an existing suggestion
45         $suggestion->{'manageddate'} = C4::Dates->today;
46         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
47         # suggesteddate, when coming from the DB, needs to be formated
48         $suggestion->{'suggesteddate'} = format_date($suggestion->{'suggesteddate'});
49     }
50     foreach my $date ( qw(rejecteddate accepteddate) ){
51     $suggestion->{$date}=(($suggestion->{$date} eq "0000-00-00" ||$suggestion->{$date} eq "")?
52                                 "":
53                                 format_date($suggestion->{$date}) 
54                               );
55     }
56     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
57 }
58
59 sub GetCriteriumDesc{
60     my ($criteriumvalue,$displayby)=@_;
61     unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED) ) {
62         return GetAuthorisedValueByCode('SUGGEST_STATUS', $criteriumvalue ) || "Unknown";
63     }
64     return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
65     return (GetBranchName($criteriumvalue)) if ($displayby =~/branchcode/);
66     return (GetSupportName($criteriumvalue)) 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 $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
81 my $op              = $input->param('op')||'else';
82 my @editsuggestions = $input->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 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field );
94 foreach (keys %$suggestion_ref){
95     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' || $op eq 'change'));
96 }
97 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
98         {
99             template_name   => "suggestion/suggestion.tmpl",
100             query           => $input,
101             type            => "intranet",
102             flagsrequired   => { catalogue => 1 },
103         }
104     );
105
106 #########################################
107 ##  Operations
108 ##
109 if ( $op =~ /save/i ) {
110         if ( $$suggestion_ref{"STATUS"} ) {
111         if ( my $tmpstatus = lc( $$suggestion_ref{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
112             $$suggestion_ref{ lc( $$suggestion_ref{"STATUS"}) . "date" } = C4::Dates->today;
113             $$suggestion_ref{ lc( $$suggestion_ref{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
114         }
115         $$suggestion_ref{"manageddate"} = C4::Dates->today;
116         $$suggestion_ref{"managedby"}   = C4::Context->userenv->{number};
117     }
118     if ( $$suggestion_ref{'suggestionid'} > 0 ) {
119         &ModSuggestion($suggestion_ref);
120     } else {
121         ###FIXME:Search here if suggestion already exists.
122         my $suggestions_loop =
123             SearchSuggestion( $suggestion_ref );
124         if (@$suggestions_loop>=1){
125             #some suggestion are answering the request Donot Add        
126         } 
127         else {    
128             ## Adding some informations related to suggestion
129             &NewSuggestion($suggestion_ref);
130         }
131         # empty fields, to avoid filter in "SearchSuggestion"
132     }  
133     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
134     $op = 'else';
135 }
136 elsif ($op=~/add/) {
137     #Adds suggestion  
138     Init($suggestion_ref);
139     $op ='save';
140
141 elsif ($op=~/edit/) {
142     #Edit suggestion  
143     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
144     Init($suggestion_ref);
145     $op ='save';
146 }  
147 elsif ($op eq "change" ) {
148     # set accepted/rejected/managed informations if applicable
149     # ie= if the librarian has choosen some action on the suggestions
150     if ($$suggestion_ref{"STATUS"} eq "ACCEPTED"){
151         $$suggestion_ref{"accepteddate"}=C4::Dates->today;
152         $$suggestion_ref{"acceptedby"}=C4::Context->userenv->{number};
153     } elsif ($$suggestion_ref{"STATUS"} eq "REJECTED"){
154         $$suggestion_ref{"rejecteddate"}=C4::Dates->today;
155         $$suggestion_ref{"rejectedby"}=C4::Context->userenv->{number};
156     }
157         if ($$suggestion_ref{"STATUS"}){
158                 $$suggestion_ref{"manageddate"}=C4::Dates->today;
159                 $$suggestion_ref{"managedby"}=C4::Context->userenv->{number};
160         }
161         if ( my $reason = $$suggestion_ref{"reason$tabcode"}){
162                 if ( $reason eq "other" ) {
163                                 $reason = $$suggestion_ref{"other_reason$tabcode"};
164                 }
165                 $$suggestion_ref{'reason'}=$reason;
166         }
167         delete $$suggestion_ref{$_} foreach ("reason$tabcode", "other_reason$tabcode");
168         foreach (keys %$suggestion_ref){
169                 delete $$suggestion_ref{$_} unless ($$suggestion_ref{$_});
170         }
171     foreach my $suggestionid (@editsuggestions) {
172         next unless $suggestionid;
173         $$suggestion_ref{'suggestionid'}=$suggestionid;
174         &ModSuggestion($suggestion_ref);
175     }
176     $op = 'else';
177 }elsif ($op eq "delete" ) {
178     foreach my $delete_field (@editsuggestions) {
179         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
180     }
181     $op = 'else';
182 }
183 elsif ( $op eq 'show' ) {
184     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
185     $$suggestion_ref{branchname} = GetBranchName $$suggestion_ref{branchcode};
186     my $budget = GetBudget $$suggestion_ref{budgetid};
187     $$suggestion_ref{budgetname} = $$budget{budget_name};
188     Init($suggestion_ref);
189 }
190 if ($op=~/else/) {
191     $op='else';
192     
193     $displayby||="STATUS";
194     delete $$suggestion_ref{'branchcode'} if($displayby eq "branchcode");
195     # distinct values of display by
196     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
197     my (@criteria_dv, $criteria_has_empty);
198     foreach (@$criteria_list) {
199         if ($_->{value}) {
200             push @criteria_dv, $_->{value};
201         } else {
202             $criteria_has_empty = 1;
203         }
204     }
205     # agregate null and empty values under empty value
206     push @criteria_dv, '' if $criteria_has_empty;
207
208     my @allsuggestions;
209     my $reasonsloop = GetAuthorisedValues("SUGGEST");
210     foreach my $criteriumvalue ( @criteria_dv ) {
211         # By default, display suggestions from current working branch
212         unless ( exists $$suggestion_ref{'branchcode'} ) {
213             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
214         }
215         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
216
217         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue );
218         $$suggestion_ref{$displayby} = $criteriumvalue;
219
220         my $suggestions = &SearchSuggestion($suggestion_ref);
221         foreach my $suggestion (@$suggestions) {
222             if ($suggestion->{budgetid}){
223                 my $bud = GetBudget( $suggestion->{budgetid} );
224                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
225             }
226             foreach my $date (qw(suggesteddate manageddate accepteddate)) {
227                 if ($suggestion->{$date} and $suggestion->{$date} ne "0000-00-00") {
228                     $suggestion->{$date} = format_date( $suggestion->{$date} );
229                 } else {
230                     $suggestion->{$date} = "";
231                 }
232             }
233         }
234         push @allsuggestions,{
235                             "suggestiontype"=>$criteriumvalue||"suggest",
236                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
237                             "suggestionscount"=>scalar(@$suggestions),             
238                             'suggestions_loop'=>$suggestions,
239                             'reasonsloop'     => $reasonsloop,
240                             };
241
242         delete $$suggestion_ref{$displayby} unless $definedvalue;
243     }
244
245     $template->param(
246         "displayby"=> $displayby,
247         "notabs"=> $displayby eq "",
248         suggestions       => \@allsuggestions,
249     );
250 }
251
252 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
253 #    $debug || warn $$suggestion_ref{$element};
254     if ($$suggestion_ref{$element}){
255         my $member=GetMember(borrowernumber=>$$suggestion_ref{$element});
256         $template->param(
257             $element."_borrowernumber"=>$$member{borrowernumber},
258             $element."_firstname"=>$$member{firstname},
259             $element."_surname"=>$$member{surname},
260             $element."_branchcode"=>$$member{branchcode},
261             $element."_description"=>$$member{description},
262             $element."_category_type"=>$$member{category_type}
263         );
264     }
265 }
266 $template->param(
267     %$suggestion_ref,  
268     "op_$op"                => 1,
269     "op"             =>$op,
270 );
271
272 if(defined($returnsuggested) and $returnsuggested ne "noone")
273 {
274         print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
275 }
276
277 ####################
278 ## Initializing selection lists
279
280 #branch display management
281 my $branchfilter = ($displayby ne "branchcode") ? $input->param('branchcode') : '';
282 my $onlymine=C4::Context->preference('IndependentBranches') &&
283             C4::Context->userenv && 
284             C4::Context->userenv->{flags}!=1 && 
285             C4::Context->userenv->{branch};
286 my $branches = GetBranches($onlymine);
287 my @branchloop;
288
289 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
290     my %row = (
291         value      => $thisbranch,
292         branchname => $branches->{$thisbranch}->{'branchname'},
293         selected   => ($branchfilter and $branches->{$thisbranch}->{'branchcode'} eq $branchfilter ) || ( $$suggestion_ref{'branchcode'} and $branches->{$thisbranch}->{'branchcode'} eq $$suggestion_ref{'branchcode'} )
294     );
295     push @branchloop, \%row;
296 }
297 $branchfilter=C4::Context->userenv->{'branch'} if ($onlymine && !$branchfilter);
298
299 $template->param( branchloop => \@branchloop,
300                 branchfilter => $branchfilter);
301
302 # the index parameter is different for item-level itemtypes
303 my $supportlist = GetSupportList();
304
305 foreach my $support (@$supportlist) {
306     $$support{'selected'} = (defined $$suggestion_ref{'itemtype'})
307         ? $$support{'itemtype'} eq $$suggestion_ref{'itemtype'}
308         : 0;
309     if ( $$support{'imageurl'} ) {
310         $$support{'imageurl'} = getitemtypeimagelocation( 'intranet', $$support{'imageurl'} );
311     } else {
312         delete $$support{'imageurl'};
313     }
314 }
315 $template->param(itemtypeloop=>$supportlist);
316 $template->param( returnsuggestedby => $returnsuggestedby );
317
318 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG",$$suggestion_ref{'patronreason'});
319 $template->param(patron_reason_loop=>$patron_reason_loop);
320
321 #Budgets management
322 my $budgets = [];
323 if ($branchfilter) {
324     my $searchbudgets = { budget_branchcode => $branchfilter };
325     $budgets = GetBudgets($searchbudgets);
326 } else {
327     $budgets = GetBudgets(undef);
328 }
329
330 my @budgets_loop;
331 foreach my $budget ( @{$budgets} ) {
332     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
333
334     ## Please see file perltidy.ERR
335     $budget->{'selected'} = 1
336         if ($$suggestion_ref{'budgetid'}
337         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
338
339     push @budgets_loop, $budget;
340 }
341
342 $template->param( budgetsloop => \@budgets_loop);
343 $template->param( "statusselected_$$suggestion_ref{'STATUS'}" =>1) if ($$suggestion_ref{'STATUS'});
344
345 # get currencies and rates
346 my @rates = GetCurrencies();
347 my $count = scalar @rates;
348 my $active_currency = GetCurrency();
349 my $selected_currency;
350 if ($$suggestion_ref{'currency'}) {
351     $selected_currency = $$suggestion_ref{'currency'};
352 }
353 else {
354     $selected_currency = $active_currency->{currency};
355 }
356
357 my @loop_currency = ();
358 for ( my $i = 0 ; $i < $count ; $i++ ) {
359     my %line;
360     $line{currcode} = $rates[$i]->{'currency'};
361     $line{rate}     = $rates[$i]->{'rate'};
362         $line{selected} = 1 if ($line{'currcode'} eq $selected_currency);
363     push @loop_currency, \%line;
364 }
365
366 $template->param(loop_currency => \@loop_currency);
367
368 $template->param(
369         price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
370         total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
371 );
372
373 # lists of distinct values (without empty) for filters
374 my %hashlists;
375 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
376     my $values_list;
377     $values_list = GetDistinctValues( "suggestions." . $field );
378     my @codes_list = map {
379         {   'code' => $$_{'value'},
380             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
381             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
382         }
383     } grep {
384         $$_{'value'}
385     } @$values_list;
386     $hashlists{ lc($field) . "_loop" } = \@codes_list;
387 }
388 $template->param(%hashlists);
389 $template->param(
390     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
391 );
392 output_html_with_http_headers $input, $cookie, $template->output;