Bug 5327 added unit tests for C4/Scheduler.pm
[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     foreach my $date qw(suggesteddate manageddate){
38         $suggestion->{$date}=(($suggestion->{$date} eq "0000-00-00" ||$suggestion->{$date} eq "")?
39                                 $suggestion->{$date}=C4::Dates->today:
40                                 format_date($suggestion->{$date}) 
41                               );
42     }               
43     foreach my $date qw(rejecteddate accepteddate){
44     $suggestion->{$date}=(($suggestion->{$date} eq "0000-00-00" ||$suggestion->{$date} eq "")?
45                                 "":
46                                 format_date($suggestion->{$date}) 
47                               );
48         }
49     $suggestion->{'managedby'}=C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
50     $suggestion->{'createdby'}=C4::Context->userenv->{"number"} unless ($suggestion->{'createdby'});
51     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
52 }
53
54 sub GetCriteriumDesc{
55     my ($criteriumvalue,$displayby)=@_;
56     return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
57     return (GetBranchName($criteriumvalue)) if ($displayby =~/branchcode/);
58     return (GetSupportName($criteriumvalue)) if ($displayby =~/itemtype/);
59     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
60         my $borr=C4::Members::GetMember(borrowernumber=>$criteriumvalue);
61         return "" unless $borr;
62         return $$borr{surname} . ", " . $$borr{firstname};
63     }
64     if ( $displayby =~ /budgetid/) {
65         my $budget = GetBudget($criteriumvalue);
66         return "" unless $budget;
67         return $$budget{budget_name};
68     }
69 }
70
71 my $input           = CGI->new;
72 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
73 my $op              = $input->param('op')||'else';
74 my @editsuggestions = $input->param('edit_field');
75 my $branchfilter   = $input->param('branchcode');
76 my $suggestedby    = $input->param('suggestedby');
77 my $returnsuggested = $input->param('returnsuggested');
78 my $returnsuggestedby = $input->param('returnsuggestedby');
79 my $managedby    = $input->param('managedby');
80 my $displayby    = $input->param('displayby');
81 my $tabcode    = $input->param('tabcode');
82
83 # filter informations which are not suggestion related.
84 my $suggestion_ref  = $input->Vars;
85
86 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field );
87 foreach (keys %$suggestion_ref){
88     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' || $op eq 'change'));
89 }
90 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
91         {
92             template_name   => "suggestion/suggestion.tmpl",
93             query           => $input,
94             type            => "intranet",
95             flagsrequired   => { catalogue => 1 },
96         }
97     );
98
99 #########################################
100 ##  Operations
101 ##
102 if ( $op =~ /save/i ) {
103         if ( $$suggestion_ref{"STATUS"} ) {
104         if ( my $tmpstatus = lc( $$suggestion_ref{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
105             $$suggestion_ref{ lc( $$suggestion_ref{"STATUS"}) . "date" } = C4::Dates->today;
106             $$suggestion_ref{ lc( $$suggestion_ref{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
107         }
108         $$suggestion_ref{"manageddate"} = C4::Dates->today;
109         $$suggestion_ref{"managedby"}   = C4::Context->userenv->{number};
110     }
111     if ( $$suggestion_ref{'suggestionid'} > 0 ) {
112         &ModSuggestion($suggestion_ref);
113     } else {
114         ###FIXME:Search here if suggestion already exists.
115         my $suggestions_loop =
116             SearchSuggestion( $suggestion_ref );
117         if (@$suggestions_loop>=1){
118             #some suggestion are answering the request Donot Add        
119         } 
120         else {    
121             ## Adding some informations related to suggestion
122             &NewSuggestion($suggestion_ref);
123         }
124         # empty fields, to avoid filter in "SearchSuggestion"
125     }  
126     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
127     $op = 'else';
128 }
129 elsif ($op=~/add/) {
130     #Adds suggestion  
131     Init($suggestion_ref);
132     $op ='save';
133
134 elsif ($op=~/edit/) {
135     #Edit suggestion  
136     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
137     Init($suggestion_ref);
138     $op ='save';
139 }  
140 elsif ($op eq "change" ) {
141     # set accepted/rejected/managed informations if applicable
142     # ie= if the librarian has choosen some action on the suggestions
143     if ($$suggestion_ref{"STATUS"} eq "ACCEPTED"){
144         $$suggestion_ref{"accepteddate"}=C4::Dates->today;
145         $$suggestion_ref{"acceptedby"}=C4::Context->userenv->{number};
146     } elsif ($$suggestion_ref{"STATUS"} eq "REJECTED"){
147         $$suggestion_ref{"rejecteddate"}=C4::Dates->today;
148         $$suggestion_ref{"rejectedby"}=C4::Context->userenv->{number};
149     }
150         if ($$suggestion_ref{"STATUS"}){
151                 $$suggestion_ref{"manageddate"}=C4::Dates->today;
152                 $$suggestion_ref{"managedby"}=C4::Context->userenv->{number};
153         }
154         if ( my $reason = $$suggestion_ref{"reason$tabcode"}){
155                 if ( $reason eq "other" ) {
156                                 $reason = $$suggestion_ref{"other_reason$tabcode"};
157                 }
158                 $$suggestion_ref{'reason'}=$reason;
159         }
160         delete $$suggestion_ref{$_} foreach ("reason$tabcode", "other_reason$tabcode");
161         foreach (keys %$suggestion_ref){
162                 delete $$suggestion_ref{$_} unless ($$suggestion_ref{$_});
163         }
164     foreach my $suggestionid (@editsuggestions) {
165         next unless $suggestionid;
166         $$suggestion_ref{'suggestionid'}=$suggestionid;
167         &ModSuggestion($suggestion_ref);
168     }
169     $op = 'else';
170 }elsif ($op eq "delete" ) {
171     foreach my $delete_field (@editsuggestions) {
172         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
173     }
174     $op = 'else';
175 }
176 if ($op=~/else/) {
177     $op='else';
178     
179     $displayby||="STATUS";
180     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
181     my @allsuggestions;
182     my $reasonsloop = GetAuthorisedValues("SUGGEST");
183     foreach my $criteriumvalue (map{$$_{'value'}} @$criteria_list){
184         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
185         
186         next if ($definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue);
187         $$suggestion_ref{$displayby}=$criteriumvalue;
188 #        warn $$suggestion_ref{$displayby}."=$criteriumvalue; $displayby";
189     
190         my $suggestions = &SearchSuggestion($suggestion_ref);
191         foreach my $suggestion (@$suggestions){
192             if($suggestion->{budgetid}) {
193                 my $budget = GetBudget($suggestion->{budgetid});
194                 $suggestion->{budget_name}=$budget->{budget_name} if $budget;
195             }
196             foreach my $date qw(suggesteddate manageddate accepteddate){
197                 if ($suggestion->{$date} ne "0000-00-00" && $suggestion->{$date} ne "" ){
198                 $suggestion->{$date}=format_date($suggestion->{$date}) ;
199                 } else {
200                 $suggestion->{$date}="" ;
201                 }             
202             }    
203         }
204         push @allsuggestions,{
205                             "suggestiontype"=>$criteriumvalue||"suggest",
206                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
207                             "suggestionscount"=>scalar(@$suggestions),             
208                             'suggestions_loop'=>$suggestions,
209                             'reasonsloop'     => $reasonsloop,
210                             };
211
212         delete $$suggestion_ref{$displayby} unless $definedvalue;
213     }
214
215     $template->param(
216         "displayby"=> $displayby,
217         "notabs"=> $displayby eq "",
218         suggestions       => \@allsuggestions,
219     );
220 }
221
222 foreach my $element qw(managedby suggestedby acceptedby) {
223 #    $debug || warn $$suggestion_ref{$element};
224     if ($$suggestion_ref{$element}){
225         my $member=GetMember(borrowernumber=>$$suggestion_ref{$element});
226         $template->param(
227             $element."_borrowernumber"=>$$member{borrowernumber},
228             $element."_firstname"=>$$member{firstname},
229             $element."_surname"=>$$member{surname},
230             $element."_branchcode"=>$$member{branchcode},
231             $element."_description"=>$$member{description},
232             $element."_category_type"=>$$member{category_type}
233         );
234     }
235 }
236 $template->param(
237     %$suggestion_ref,  
238     "op_$op"                => 1,
239     dateformat    => C4::Context->preference("dateformat"),
240     "op"             =>$op,
241 );
242
243 if(defined($returnsuggested) and $returnsuggested ne "noone")
244 {
245         print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
246 }
247
248 ####################
249 ## Initializing selection lists
250
251 #branch display management
252 my $onlymine=C4::Context->preference('IndependantBranches') && 
253             C4::Context->userenv && 
254             C4::Context->userenv->{flags}!=1 && 
255             C4::Context->userenv->{branch};
256 my $branches = GetBranches($onlymine);
257 my @branchloop;
258
259 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
260     my %row = (
261         value      => $thisbranch,
262         branchname => $branches->{$thisbranch}->{'branchname'},
263         selected   => ($branches->{$thisbranch}->{'branchcode'} eq $branchfilter)
264                     ||($branches->{$thisbranch}->{'branchcode'} eq $$suggestion_ref{'branchcode'})    
265     );
266     push @branchloop, \%row;
267 }
268 $branchfilter=C4::Context->userenv->{'branch'} if ($onlymine && !$branchfilter);
269
270 $template->param( branchloop => \@branchloop,
271                 branchfilter => $branchfilter);
272
273 # the index parameter is different for item-level itemtypes
274 my $supportlist=GetSupportList();                               
275 foreach my $support(@$supportlist){
276     $$support{'selected'}= $$support{'itemtype'} eq $$suggestion_ref{'itemtype'};
277     if ($$support{'imageurl'}){
278         $$support{'imageurl'}= getitemtypeimagelocation( 'intranet', $$support{'imageurl'} );
279     }
280     else {
281     delete $$support{'imageurl'}
282     }
283 }
284 $template->param(itemtypeloop=>$supportlist);
285 $template->param( returnsuggestedby => $returnsuggestedby );
286
287 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG",$$suggestion_ref{'patronreason'});
288 $template->param(patron_reason_loop=>$patron_reason_loop);
289
290 #Budgets management
291 my $budgets = [];
292 if ($branchfilter) {
293     my $searchbudgets = { budget_branchcode => $branchfilter };
294     $budgets = GetBudgets($searchbudgets);
295 } else {
296     $budgets = GetBudgets(undef);
297 }
298
299 foreach my $budget ( @{$budgets} ) {
300 ## Please see file perltidy.ERR
301     $budget->{'selected'}=1 if ($$suggestion_ref{'budgetid'} && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'})
302 };
303
304 $template->param( budgetsloop => $budgets);
305 $template->param( "statusselected_$$suggestion_ref{'STATUS'}" =>1);
306
307 # get currencies and rates
308 my @rates = GetCurrencies();
309 my $count = scalar @rates;
310 my $active_currency = GetCurrency();
311 my $selected_currency;
312 if ($$suggestion_ref{'currency'}) {
313     $selected_currency = $$suggestion_ref{'currency'};
314 }
315 else {
316     $selected_currency = $active_currency->{currency};
317 }
318
319 my @loop_currency = ();
320 for ( my $i = 0 ; $i < $count ; $i++ ) {
321     my %line;
322     $line{currcode} = $rates[$i]->{'currency'};
323     $line{rate}     = $rates[$i]->{'rate'};
324         $line{selected} = 1 if ($line{'currcode'} eq $selected_currency);
325     push @loop_currency, \%line;
326 }
327
328 $template->param(loop_currency => \@loop_currency);
329
330 $template->param(
331         price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
332         total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
333 );
334
335 my %hashlists;
336 foreach my $field qw(managedby acceptedby suggestedby budgetid) {
337     my $values_list;
338     $values_list=GetDistinctValues("suggestions.".$field) ;
339     my @codes_list = map{
340                         { 'code'=>$$_{'value'},
341                         'desc'=>GetCriteriumDesc($$_{'value'},$field),
342                         'selected'=> $$_{'value'} eq $$suggestion_ref{$field}
343                         }
344                     } @$values_list;
345     $hashlists{lc($field)."_loop"}=\@codes_list;
346 }
347 $template->param(%hashlists);
348 $template->param(DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),);
349 output_html_with_http_headers $input, $cookie, $template->output;