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