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