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