Bug 17835: Add an additional LEFT JOIN condition using DBIx::Class
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 require Exporter;
23 use CGI qw ( -utf8 );
24 use C4::Auth;    # get_template_and_user
25 use C4::Output;
26 use C4::Suggestions;
27 use C4::Koha;
28 use C4::Budgets;
29 use C4::Search;
30 use C4::Members;
31 use C4::Debug;
32
33 use Koha::DateUtils qw( dt_from_string );
34 use Koha::AuthorisedValues;
35 use Koha::Acquisition::Currencies;
36 use Koha::Libraries;
37
38 use URI::Escape;
39
40 sub Init{
41     my $suggestion= shift @_;
42     # "Managed by" is used only when a suggestion is being edited (not when created)
43     if ($suggestion->{'suggesteddate'} eq "0000-00-00" ||$suggestion->{'suggesteddate'} eq "") {
44         # new suggestion
45         $suggestion->{suggesteddate} = dt_from_string;
46         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
47     }
48     else {
49         # editing of an existing suggestion
50         $suggestion->{manageddate} = dt_from_string;
51         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
52     }
53     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
54 }
55
56 sub GetCriteriumDesc{
57     my ($criteriumvalue,$displayby)=@_;
58     if ($displayby =~ /status/i) {
59         unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
60             my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
61             return $av->count ? $av->next->lib : 'Unkown';
62         }
63         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
64     }
65     return Koha::Libraries->find($criteriumvalue)->branchname
66         if $displayby =~ /branchcode/;
67     if ( $displayby =~ /itemtype/ ) {
68         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
69         return $av->count ? $av->next->lib : 'Unkown';
70     }
71     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
72         my $borr=C4::Members::GetMember(borrowernumber=>$criteriumvalue);
73         return "" unless $borr;
74         return $$borr{surname} . ", " . $$borr{firstname};
75     }
76     if ( $displayby =~ /budgetid/) {
77         my $budget = GetBudget($criteriumvalue);
78         return "" unless $budget;
79         return $$budget{budget_name};
80     }
81 }
82
83 my $input           = CGI->new;
84 my $redirect  = $input->param('redirect');
85 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
86 my $op              = $input->param('op')||'else';
87 my @editsuggestions = $input->multi_param('edit_field');
88 my $suggestedby     = $input->param('suggestedby');
89 my $returnsuggestedby = $input->param('returnsuggestedby');
90 my $returnsuggested = $input->param('returnsuggested');
91 my $managedby       = $input->param('managedby');
92 my $displayby       = $input->param('displayby') || '';
93 my $tabcode         = $input->param('tabcode');
94
95 # filter informations which are not suggestion related.
96 my $suggestion_ref  = $input->Vars;
97
98 # get only the columns of Suggestion
99 my $schema = Koha::Database->new()->schema;
100 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
101 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
102 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
103
104 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode edit_field );
105 foreach (keys %$suggestion_ref){
106     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' || $op eq 'change'));
107 }
108 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
109         {
110             template_name   => "suggestion/suggestion.tt",
111             query           => $input,
112             type            => "intranet",
113             flagsrequired   => { catalogue => 1 },
114         }
115     );
116
117 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
118 $template->param('borrowernumber' => $borrowernumber);
119
120 #########################################
121 ##  Operations
122 ##
123 if ( $op =~ /save/i ) {
124     $suggestion_only->{suggesteddate} = dt_from_string( $suggestion_only->{suggesteddate} )
125         if $suggestion_only->{suggesteddate};
126
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             my @messages;
144             for my $suggestion ( @$suggestions_loop ) {
145                 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
146             }
147             $template->param( messages => \@messages );
148         } 
149         else {    
150             ## Adding some informations related to suggestion
151             &NewSuggestion($suggestion_only);
152         }
153         # empty fields, to avoid filter in "SearchSuggestion"
154     }  
155     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
156     $op = 'else';
157
158     if( $redirect eq 'purchase_suggestions' ) {
159         print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
160     }
161
162 }
163 elsif ($op=~/add/) {
164     #Adds suggestion  
165     Init($suggestion_ref);
166     $op ='save';
167
168 elsif ($op=~/edit/) {
169     #Edit suggestion  
170     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
171     Init($suggestion_ref);
172     $op ='save';
173 }  
174 elsif ($op eq "change" ) {
175     # set accepted/rejected/managed informations if applicable
176     # ie= if the librarian has chosen some action on the suggestions
177     if ($suggestion_only->{"STATUS"} eq "ACCEPTED"){
178         $suggestion_only->{accepteddate} = dt_from_string;
179         $suggestion_only->{"acceptedby"}=C4::Context->userenv->{number};
180     } elsif ($suggestion_only->{"STATUS"} eq "REJECTED"){
181         $suggestion_only->{rejecteddate} = dt_from_string;
182         $suggestion_only->{"rejectedby"}=C4::Context->userenv->{number};
183     }
184     if ($suggestion_only->{"STATUS"}){
185         $suggestion_only->{manageddate} = dt_from_string;
186         $suggestion_only->{"managedby"}=C4::Context->userenv->{number};
187     }
188     if ( my $reason = $$suggestion_ref{"reason$tabcode"}){
189         if ( $reason eq "other" ) {
190             $reason = $$suggestion_ref{"other_reason$tabcode"};
191         }
192         $suggestion_only->{reason}=$reason;
193     }
194
195     foreach my $suggestionid (@editsuggestions) {
196         next unless $suggestionid;
197         $suggestion_only->{'suggestionid'}=$suggestionid;
198         &ModSuggestion($suggestion_only);
199     }
200     my $params = '';
201     foreach my $key (
202         qw(
203         displayby branchcode title author isbn publishercode copyrightdate
204         collectiontitle suggestedby suggesteddate_from suggesteddate_to
205         manageddate_from manageddate_to accepteddate_from
206         accepteddate_to budgetid
207         )
208       )
209     {
210         $params .= $key . '=' . uri_escape($input->param($key)) . '&'
211           if defined($input->param($key));
212     }
213     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
214 }elsif ($op eq "delete" ) {
215     foreach my $delete_field (@editsuggestions) {
216         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
217     }
218     $op = 'else';
219 }
220 elsif ( $op eq 'show' ) {
221     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
222     my $budget = GetBudget $$suggestion_ref{budgetid};
223     $$suggestion_ref{budgetname} = $$budget{budget_name};
224     Init($suggestion_ref);
225 }
226 if ($op=~/else/) {
227     $op='else';
228     
229     $displayby||="STATUS";
230     delete $$suggestion_ref{'branchcode'} if($displayby eq "branchcode");
231     # distinct values of display by
232     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
233     my (@criteria_dv, $criteria_has_empty);
234     foreach (@$criteria_list) {
235         if ($_->{value}) {
236             push @criteria_dv, $_->{value};
237         } else {
238             $criteria_has_empty = 1;
239         }
240     }
241     # aggregate null and empty values under empty value
242     push @criteria_dv, '' if $criteria_has_empty;
243
244     my @allsuggestions;
245     my $reasonsloop = GetAuthorisedValues("SUGGEST");
246     foreach my $criteriumvalue ( @criteria_dv ) {
247         # By default, display suggestions from current working branch
248         unless ( exists $$suggestion_ref{'branchcode'} ) {
249             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
250         }
251         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
252
253         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue );
254         $$suggestion_ref{$displayby} = $criteriumvalue;
255
256         my $suggestions = &SearchSuggestion($suggestion_ref);
257         foreach my $suggestion (@$suggestions) {
258             if ($suggestion->{budgetid}){
259                 my $bud = GetBudget( $suggestion->{budgetid} );
260                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
261             }
262         }
263         push @allsuggestions,{
264                             "suggestiontype"=>$criteriumvalue||"suggest",
265                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
266                             "suggestionscount"=>scalar(@$suggestions),             
267                             'suggestions_loop'=>$suggestions,
268                             'reasonsloop'     => $reasonsloop,
269                             };
270
271         delete $$suggestion_ref{$displayby} unless $definedvalue;
272     }
273
274     $template->param(
275         "displayby"=> $displayby,
276         "notabs"=> $displayby eq "",
277         suggestions       => \@allsuggestions,
278     );
279 }
280
281 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
282 #    $debug || warn $$suggestion_ref{$element};
283     if ($$suggestion_ref{$element}){
284         my $member=GetMember(borrowernumber=>$$suggestion_ref{$element});
285         $template->param(
286             $element."_borrowernumber"=>$$member{borrowernumber},
287             $element."_firstname"=>$$member{firstname},
288             $element."_surname"=>$$member{surname},
289             $element."_branchcode"=>$$member{branchcode},
290             $element."_description"=>$$member{description},
291             $element."_category_type"=>$$member{category_type}
292         );
293     }
294 }
295 $template->param(
296     %$suggestion_ref,  
297     "op_$op"                => 1,
298     "op"             =>$op,
299 );
300
301 if(defined($returnsuggested) and $returnsuggested ne "noone")
302 {
303     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
304 }
305
306 my $branchfilter = ($displayby ne "branchcode") ? $input->param('branchcode') : C4::Context->userenv->{'branch'};
307
308 $template->param(
309     branchfilter => $branchfilter,
310 );
311
312 $template->param( returnsuggestedby => $returnsuggestedby );
313
314 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
315 $template->param(patron_reason_loop=>$patron_reason_loop);
316
317 #Budgets management
318 my $budgets = [];
319 if ($branchfilter) {
320     my $searchbudgets = { budget_branchcode => $branchfilter };
321     $budgets = GetBudgets($searchbudgets);
322 } else {
323     $budgets = GetBudgets(undef);
324 }
325
326 my @budgets_loop;
327 foreach my $budget ( @{$budgets} ) {
328     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
329
330     ## Please see file perltidy.ERR
331     $budget->{'selected'} = 1
332         if ($$suggestion_ref{'budgetid'}
333         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
334
335     push @budgets_loop, $budget;
336 }
337
338 $template->param( budgetsloop => \@budgets_loop);
339 $template->param( "statusselected_$$suggestion_ref{'STATUS'}" =>1) if ($$suggestion_ref{'STATUS'});
340
341 my @currencies = Koha::Acquisition::Currencies->search;
342 $template->param(
343     currencies   => \@currencies,
344     suggestion   => $suggestion_ref,
345     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
346     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
347 );
348
349 # lists of distinct values (without empty) for filters
350 my %hashlists;
351 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
352     my $values_list;
353     $values_list = GetDistinctValues( "suggestions." . $field );
354     my @codes_list = map {
355         {   'code' => $$_{'value'},
356             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
357             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
358         }
359     } grep {
360         $$_{'value'}
361     } @$values_list;
362     $hashlists{ lc($field) . "_loop" } = \@codes_list;
363 }
364
365 $template->param(
366     %hashlists,
367     borrowernumber           => ($input->param('borrowernumber') // undef),
368     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
369 );
370 output_html_with_http_headers $input, $cookie, $template->output;