Bug 7047: Storing subscription renewal note in suggestion to be displayed on the...
[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 Modern::Perl;
21 require Exporter;
22 use CGI qw ( -utf8 );
23 use C4::Auth;    # get_template_and_user
24 use C4::Output;
25 use C4::Suggestions;
26 use C4::Koha;
27 use C4::Budgets;
28 use C4::Search;
29 use C4::Members;
30 use C4::Debug;
31 use Koha::DateUtils qw( dt_from_string );
32 use Koha::AuthorisedValues;
33 use Koha::Acquisition::Currencies;
34 use Koha::Libraries;
35 use Koha::Patrons;
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} = dt_from_string;
45         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
46     }
47     else {
48         # editing of an existing suggestion
49         $suggestion->{manageddate} = dt_from_string;
50         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
51     }
52     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
53 }
54
55 sub GetCriteriumDesc{
56     my ($criteriumvalue,$displayby)=@_;
57     if ($displayby =~ /status/i) {
58         unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
59             my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
60             return $av->count ? $av->next->lib : 'Unknown';
61         }
62         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
63     }
64     return Koha::Libraries->find($criteriumvalue)->branchname
65         if $displayby =~ /branchcode/;
66     if ( $displayby =~ /itemtype/ ) {
67         my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue });
68         return $av->count ? $av->next->lib : 'Unknown';
69     }
70     if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){
71         my $patron = Koha::Patrons->find( $criteriumvalue );
72         return "" unless $patron;
73         return $patron->surname . ", " . $patron->firstname;
74     }
75     if ( $displayby =~ /budgetid/) {
76         my $budget = GetBudget($criteriumvalue);
77         return "" unless $budget;
78         return $$budget{budget_name};
79     }
80 }
81
82 my $input           = CGI->new;
83 my $redirect  = $input->param('redirect');
84 my $suggestedbyme   = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1);
85 my $op              = $input->param('op')||'else';
86 my @editsuggestions = $input->multi_param('edit_field');
87 my $suggestedby     = $input->param('suggestedby');
88 my $returnsuggestedby = $input->param('returnsuggestedby');
89 my $returnsuggested = $input->param('returnsuggested');
90 my $managedby       = $input->param('managedby');
91 my $displayby       = $input->param('displayby') || '';
92 my $tabcode         = $input->param('tabcode');
93 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
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   => { acquisition => 'suggestions_manage' },
114         }
115     );
116
117 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
118 $template->param('borrowernumber' => $borrowernumber);
119 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
120
121 #########################################
122 ##  Operations
123 ##
124 if ( $op =~ /save/i ) {
125
126     for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
127         $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
128             if $suggestion_only->{$date_key};
129     }
130
131     if ( $suggestion_only->{"STATUS"} ) {
132         if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
133             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
134             $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
135         }
136         $suggestion_only->{manageddate} = dt_from_string;
137         $suggestion_only->{"managedby"}   = C4::Context->userenv->{number};
138     }
139
140     my $otherreason = $input->param('other_reason');
141     if ($suggestion_only->{reason} eq 'other' && $otherreason) {
142         $suggestion_only->{reason} = $otherreason;
143     }
144
145     if ( $suggestion_only->{'suggestionid'} > 0 ) {
146         &ModSuggestion($suggestion_only);
147     } else {
148         ###FIXME:Search here if suggestion already exists.
149         my $suggestions_loop =
150             SearchSuggestion( $suggestion_only );
151         if (@$suggestions_loop>=1){
152             #some suggestion are answering the request Donot Add
153             my @messages;
154             for my $suggestion ( @$suggestions_loop ) {
155                 push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
156             }
157             $template->param( messages => \@messages );
158         } 
159         else {    
160             ## Adding some informations related to suggestion
161             &NewSuggestion($suggestion_only);
162         }
163         # empty fields, to avoid filter in "SearchSuggestion"
164     }  
165     map{delete $$suggestion_ref{$_}} keys %$suggestion_ref;
166     $op = 'else';
167
168     if( $redirect eq 'purchase_suggestions' ) {
169         print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
170     }
171
172 }
173 elsif ($op=~/add/) {
174     #Adds suggestion  
175     Init($suggestion_ref);
176     $op ='save';
177
178 elsif ($op=~/edit/) {
179     #Edit suggestion  
180     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
181     $suggestion_ref->{reasonsloop} = $reasonsloop;
182     my $other_reason = 1;
183     foreach my $reason ( @{ $reasonsloop } ) {
184         if ($suggestion_ref->{reason} eq $reason->{lib}) {
185             $other_reason = 0;
186         }
187     }
188     $other_reason = 0 unless $suggestion_ref->{reason};
189     $template->param(other_reason => $other_reason);
190     Init($suggestion_ref);
191     $op ='save';
192 }  
193 elsif ($op eq "change" ) {
194
195     my $suggestion;
196     # set accepted/rejected/managed informations if applicable
197     # ie= if the librarian has chosen some action on the suggestions
198     my $STATUS      = $input->param('STATUS');
199     my $accepted_by = $input->param('acceptedby');
200     if ( $STATUS eq "ACCEPTED" ) {
201         $suggestion = {
202             accepteddate => dt_from_string,
203             acceptedby => C4::Context->userenv->{number},
204         };
205     }
206     elsif ( $STATUS eq "REJECTED" ) {
207         $suggestion = {
208             rejecteddate => dt_from_string,
209             rejectedby   => C4::Context->userenv->{number},
210         };
211     }
212     if ($STATUS) {
213         $suggestion->{manageddate} = dt_from_string;
214         $suggestion->{managedby}   = C4::Context->userenv->{number};
215         $suggestion->{STATUS}      = $STATUS;
216     }
217     if ( my $reason = $input->param("reason$tabcode") ) {
218         if ( $reason eq "other" ) {
219             $reason = $input->param("other_reason$tabcode");
220         }
221         $suggestion->{reason} = $reason;
222     }
223
224     foreach my $suggestionid (@editsuggestions) {
225         next unless $suggestionid;
226         $suggestion->{suggestionid} = $suggestionid;
227         &ModSuggestion($suggestion);
228     }
229     my $params = '';
230     foreach my $key (
231         qw(
232         displayby branchcode title author isbn publishercode copyrightdate
233         collectiontitle suggestedby suggesteddate_from suggesteddate_to
234         manageddate_from manageddate_to accepteddate_from
235         accepteddate_to budgetid
236         )
237       )
238     {
239         $params .= $key . '=' . uri_escape($input->param($key)) . '&'
240           if defined($input->param($key));
241     }
242     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
243 }elsif ($op eq "delete" ) {
244     foreach my $delete_field (@editsuggestions) {
245         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
246     }
247     $op = 'else';
248 }
249 elsif ( $op eq 'show' ) {
250     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
251     my $budget = GetBudget $$suggestion_ref{budgetid};
252     $$suggestion_ref{budgetname} = $$budget{budget_name};
253     Init($suggestion_ref);
254 }
255 if ($op=~/else/) {
256     $op='else';
257     
258     $displayby||="STATUS";
259     # distinct values of display by
260     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
261     my (@criteria_dv, $criteria_has_empty);
262     foreach (@$criteria_list) {
263         if ($_->{value}) {
264             push @criteria_dv, $_->{value};
265         } else {
266             $criteria_has_empty = 1;
267         }
268     }
269     # aggregate null and empty values under empty value
270     push @criteria_dv, '' if $criteria_has_empty;
271
272     # Hack to not modify GetDistinctValues for this specific case
273     if (   $displayby eq 'branchcode'
274         && C4::Context->preference('IndependentBranches')
275         && not C4::Context->IsSuperLibrarian )
276     {
277         @criteria_dv = ( C4::Context->userenv->{'branch'} );
278     }
279
280     my @allsuggestions;
281     foreach my $criteriumvalue ( @criteria_dv ) {
282         # By default, display suggestions from current working branch
283         unless ( exists $$suggestion_ref{'branchcode'} ) {
284             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
285         }
286         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
287
288         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' or $branchfilter ne '__ANY__' );
289         $$suggestion_ref{$displayby} = $criteriumvalue;
290
291         my $suggestions = &SearchSuggestion($suggestion_ref);
292         foreach my $suggestion (@$suggestions) {
293             if ($suggestion->{budgetid}){
294                 my $bud = GetBudget( $suggestion->{budgetid} );
295                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
296             }
297         }
298         push @allsuggestions,{
299                             "suggestiontype"=>$criteriumvalue||"suggest",
300                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
301                             "suggestionscount"=>scalar(@$suggestions),             
302                             'suggestions_loop'=>$suggestions,
303                             'reasonsloop'     => $reasonsloop,
304                             };
305
306         delete $$suggestion_ref{$displayby} unless $definedvalue;
307     }
308
309     $template->param(
310         "displayby"=> $displayby,
311         "notabs"=> $displayby eq "",
312         suggestions       => \@allsuggestions,
313     );
314 }
315
316 foreach my $element ( qw(managedby suggestedby acceptedby) ) {
317 #    $debug || warn $$suggestion_ref{$element};
318     if ($$suggestion_ref{$element}){
319         my $patron = Koha::Patrons->find( $$suggestion_ref{$element} );
320         my $category = $patron->category;
321         $template->param(
322             $element."_borrowernumber"=>$patron->borrowernumber,
323             $element."_firstname"=>$patron->firstname,
324             $element."_surname"=>$patron->surname,
325             $element."_cardnumber"=>$patron->cardnumber,
326             $element."_branchcode"=>$patron->branchcode,
327             $element."_description"=>$category->description,
328             $element."_category_type"=>$category->category_type,
329         );
330     }
331 }
332 $template->param(
333     %$suggestion_ref,  
334     "op_$op"                => 1,
335     "op"             =>$op,
336 );
337
338 if(defined($returnsuggested) and $returnsuggested ne "noone")
339 {
340     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
341 }
342
343 $template->param(
344     branchfilter => $branchfilter,
345 );
346
347 $template->param( returnsuggestedby => $returnsuggestedby );
348
349 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
350 $template->param(patron_reason_loop=>$patron_reason_loop);
351
352 #Budgets management
353 my $budgets = GetBudgets;
354 my @budgets_loop;
355 foreach my $budget ( @{$budgets} ) {
356     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
357
358     ## Please see file perltidy.ERR
359     $budget->{'selected'} = 1
360         if ($$suggestion_ref{'budgetid'}
361         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
362
363     push @budgets_loop, $budget;
364 }
365
366 $template->param( budgetsloop => \@budgets_loop);
367 if( $suggestion_ref->{STATUS} ) {
368     $template->param(
369         "statusselected_".$suggestion_ref->{STATUS} => 1,
370         selected_status => $suggestion_ref->{STATUS}, # We need template var selected_status in the second part of the template where template var suggestion.STATUS is out of scope
371     );
372 }
373
374 my @currencies = Koha::Acquisition::Currencies->search;
375 $template->param(
376     currencies   => \@currencies,
377     suggestion   => $suggestion_ref,
378     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
379     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
380 );
381
382 # lists of distinct values (without empty) for filters
383 my %hashlists;
384 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
385     my $values_list;
386     $values_list = GetDistinctValues( "suggestions." . $field );
387     my @codes_list = map {
388         {   'code' => $$_{'value'},
389             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
390             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
391         }
392     } grep {
393         $$_{'value'}
394     } @$values_list;
395     $hashlists{ lc($field) . "_loop" } = \@codes_list;
396 }
397
398 $template->param(
399     %hashlists,
400     borrowernumber           => ($input->param('borrowernumber') // undef),
401     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
402 );
403 output_html_with_http_headers $input, $cookie, $template->output;