Bug 30717: (QA follow-up) Move to module
[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 qw( get_template_and_user );
24 use C4::Output qw( output_html_with_http_headers );
25 use C4::Suggestions;
26 use C4::Koha qw( GetAuthorisedValues );
27 use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget );
28 use C4::Search qw( FindDuplicate GetDistinctValues );
29 use C4::Members;
30 use Koha::DateUtils qw( dt_from_string );
31 use Koha::AuthorisedValues;
32 use Koha::Acquisition::Currencies;
33 use Koha::Libraries;
34 use Koha::Patrons;
35
36 use URI::Escape qw( uri_escape );
37
38 sub Init{
39     my $suggestion= shift @_;
40     # "Managed by" is used only when a suggestion is being edited (not when created)
41     if ($suggestion->{'suggesteddate'} eq "") {
42         # new suggestion
43         $suggestion->{suggesteddate} = dt_from_string;
44         $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'});
45     }
46     else {
47         # editing of an existing suggestion
48         $suggestion->{manageddate} = dt_from_string;
49         $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'});
50     }
51     $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'});
52 }
53
54 sub GetCriteriumDesc{
55     my ($criteriumvalue,$displayby)=@_;
56     if ($displayby =~ /status/i) {
57         unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) {
58             my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue });
59             return $av->count ? $av->next->lib : 'Unknown';
60         }
61         return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i);
62     }
63     if ( $displayby =~ /branchcode/ ) {
64         return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__";
65     }
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('suggestionid');
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 $save_confirmed  = $input->param('save_confirmed') || 0;
94 my $notify          = $input->param('notify');
95 my $filter_archived = $input->param('filter_archived');
96
97 my $reasonsloop     = GetAuthorisedValues("SUGGEST");
98
99 # filter informations which are not suggestion related.
100 my $suggestion_ref  = { %{$input->Vars} }; # Copying, otherwise $input will be modified
101
102 # get only the columns of Suggestion
103 my $schema = Koha::Database->new()->schema;
104 my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' ';
105 my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref };
106 $suggestion_only->{STATUS} = $suggestion_ref->{STATUS};
107
108 delete $$suggestion_ref{$_} foreach qw( suggestedbyme op displayby tabcode notify filter_archived );
109 foreach (keys %$suggestion_ref){
110     delete $$suggestion_ref{$_} if (!$$suggestion_ref{$_} && ($op eq 'else' ));
111 }
112 my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user(
113         {
114             template_name   => "suggestion/suggestion.tt",
115             query           => $input,
116             type            => "intranet",
117             flagsrequired   => { suggestions => 'suggestions_manage' },
118         }
119     );
120
121 $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') );
122 $template->param('borrowernumber' => $borrowernumber);
123 my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'};
124
125 #########################################
126 ##  Operations
127 ##
128
129 if ( $op =~ /save/i ) {
130     my @messages;
131     my $biblio = MarcRecordFromNewSuggestion({
132             title => $suggestion_only->{title},
133             author => $suggestion_only->{author},
134             itemtype => $suggestion_only->{itemtype},
135     });
136
137     my $manager = Koha::Patrons->find( $suggestion_only->{managedby} );
138     if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) {
139         push @messages, { type => 'error', code => 'manager_not_enough_permissions' };
140         $template->param(
141             messages => \@messages,
142         );
143         delete $suggestion_ref->{suggesteddate};
144         delete $suggestion_ref->{manageddate};
145         delete $suggestion_ref->{managedby};
146         Init($suggestion_ref);
147     }
148     elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) {
149         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
150         $template->param(
151             messages => \@messages,
152             need_confirm => 1
153         );
154         delete $suggestion_ref->{suggesteddate};
155         delete $suggestion_ref->{manageddate};
156         Init($suggestion_ref);
157     }
158     else {
159
160         for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) {
161             $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} )
162                 if $suggestion_only->{$date_key};
163         }
164
165         if ( $suggestion_only->{"STATUS"} ) {
166             if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) {
167                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string;
168                 $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" }   = C4::Context->userenv->{number};
169             }
170             $suggestion_only->{manageddate} = dt_from_string;
171             $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number};
172         }
173
174         my $otherreason = $input->param('other_reason');
175         if ($suggestion_only->{reason} eq 'other' && $otherreason) {
176             $suggestion_only->{reason} = $otherreason;
177         }
178
179         if ( $suggestion_only->{'suggestionid'} > 0 ) {
180
181             $suggestion_only->{lastmodificationdate} = dt_from_string;
182             $suggestion_only->{lastmodificationby}   = C4::Context->userenv->{number};
183             $suggestion_only->{branchcode} = undef
184               if exists $suggestion_only->{branchcode}
185               && $suggestion_only->{branchcode} eq "";
186
187             &ModSuggestion($suggestion_only);
188
189             if ( $notify ) {
190                 my $patron = Koha::Patrons->find( $suggestion_only->{managedby} );
191                 my $email_address = $patron->notice_email_address;
192                 if ($patron->notice_email_address) {
193
194                     my $letter = C4::Letters::GetPreparedLetter(
195                         module      => 'suggestions',
196                         letter_code => 'NOTIFY_MANAGER',
197                         branchcode  => $patron->branchcode,
198                         lang        => $patron->lang,
199                         tables      => {
200                             suggestions => $suggestion_only->{suggestionid},
201                             branches    => $patron->branchcode,
202                             borrowers   => $patron->borrowernumber,
203                         },
204                     );
205                     C4::Letters::EnqueueLetter(
206                         {
207                             letter                 => $letter,
208                             borrowernumber         => $patron->borrowernumber,
209                             message_transport_type => 'email'
210                         }
211                     );
212                 }
213             }
214         } else {
215             ###FIXME:Search here if suggestion already exists.
216             my $suggestions_loop =
217                 SearchSuggestion( $suggestion_only );
218             if (@$suggestions_loop>=1){
219                 #some suggestion are answering the request Donot Add
220                 my @messages;
221                 for my $suggestion ( @$suggestions_loop ) {
222                     push @messages, { type => 'error', code => 'already_exists', id => $suggestion->{suggestionid} };
223                 }
224                 $template->param( messages => \@messages );
225             }
226             else {
227                 ## Adding some informations related to suggestion
228                 &NewSuggestion($suggestion_only);
229             }
230             # empty fields, to avoid filter in "SearchSuggestion"
231         }
232         map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref;
233         $op = 'else';
234
235         if( $redirect eq 'purchase_suggestions' ) {
236             print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber");
237         }
238     }
239 }
240 elsif ($op=~/add/) {
241     #Adds suggestion
242     Init($suggestion_ref);
243     $op ='save';
244 }
245 elsif ($op=~/edit/) {
246     #Edit suggestion  
247     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
248     $suggestion_ref->{reasonsloop} = $reasonsloop;
249     my $other_reason = 1;
250     foreach my $reason ( @{ $reasonsloop } ) {
251         if ($suggestion_ref->{reason} eq $reason->{lib}) {
252             $other_reason = 0;
253         }
254     }
255     $other_reason = 0 unless $suggestion_ref->{reason};
256     $template->param(other_reason => $other_reason);
257     Init($suggestion_ref);
258     $op ='save';
259 }  
260 elsif ($op eq "update_status" ) {
261
262     my $suggestion;
263     # set accepted/rejected/managed informations if applicable
264     # ie= if the librarian has chosen some action on the suggestions
265     my $STATUS      = $input->param('STATUS');
266     my $accepted_by = $input->param('acceptedby');
267     if ( $STATUS eq "ACCEPTED" ) {
268         $suggestion = {
269             accepteddate => dt_from_string,
270             acceptedby => C4::Context->userenv->{number},
271         };
272     }
273     elsif ( $STATUS eq "REJECTED" ) {
274         $suggestion = {
275             rejecteddate => dt_from_string,
276             rejectedby   => C4::Context->userenv->{number},
277         };
278     }
279     if ($STATUS) {
280         $suggestion->{manageddate} = dt_from_string;
281         $suggestion->{managedby}   = C4::Context->userenv->{number};
282         $suggestion->{STATUS}      = $STATUS;
283     }
284     if ( my $reason = $input->param("reason") ) {
285         if ( $reason eq "other" ) {
286             $reason = $input->param("other_reason");
287         }
288         $suggestion->{reason} = $reason;
289     }
290
291     foreach my $suggestionid (@editsuggestions) {
292         next unless $suggestionid;
293         $suggestion->{suggestionid} = $suggestionid;
294         &ModSuggestion($suggestion);
295     }
296     redirect_with_params($input);
297 }elsif ($op eq "delete" ) {
298     foreach my $delete_field (@editsuggestions) {
299         &DelSuggestion( $borrowernumber, $delete_field,'intranet' );
300     }
301     redirect_with_params($input);
302 }
303 elsif ($op eq "archive" ) {
304     Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions;
305
306     redirect_with_params($input);
307 }
308 elsif ($op eq "unarchive" ) {
309     Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions;
310
311     redirect_with_params($input);
312 }
313 elsif ( $op eq 'update_itemtype' ) {
314     my $new_itemtype = $input->param('suggestion_itemtype');
315     foreach my $suggestionid (@editsuggestions) {
316         next unless $suggestionid;
317         &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype });
318     }
319     redirect_with_params($input);
320 }
321 elsif ( $op eq 'update_manager' ) {
322     my $managedby = $input->param('suggestion_managedby');
323     foreach my $suggestionid (@editsuggestions) {
324         next unless $suggestionid;
325         &ModSuggestion({ suggestionid => $suggestionid, managedby => $managedby });
326     }
327     redirect_with_params($input);
328 }
329 elsif ( $op eq 'show' ) {
330     $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'});
331     my $budget = GetBudget $$suggestion_ref{budgetid};
332     $$suggestion_ref{budgetname} = $$budget{budget_name};
333     Init($suggestion_ref);
334 }
335 if ($op=~/else/) {
336     $op='else';
337
338     $displayby||="STATUS";
339     # distinct values of display by
340     my $criteria_list=GetDistinctValues("suggestions.".$displayby);
341     my (@criteria_dv, $criteria_has_empty);
342     foreach (@$criteria_list) {
343         if ($_->{value}) {
344             push @criteria_dv, $_->{value};
345         } else {
346             $criteria_has_empty = 1;
347         }
348     }
349     # aggregate null and empty values under empty value
350     push @criteria_dv, '' if $criteria_has_empty;
351
352     # Hack to not modify GetDistinctValues for this specific case
353     if (   $displayby eq 'branchcode'
354         && C4::Context->preference('IndependentBranches')
355         && not C4::Context->IsSuperLibrarian )
356     {
357         @criteria_dv = ( C4::Context->userenv->{'branch'} );
358     }
359     # Pending tab first
360     if ( $displayby eq 'STATUS' ) {
361         @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv;
362         unshift @criteria_dv, 'ASKED';
363     }
364
365     my @allsuggestions;
366     foreach my $criteriumvalue ( @criteria_dv ) {
367         # By default, display suggestions from current working branch
368         unless ( exists $$suggestion_ref{'branchcode'} ) {
369             $$suggestion_ref{'branchcode'} = C4::Context->userenv->{'branch'};
370         }
371         my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne "";
372
373         next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' );
374         $$suggestion_ref{$displayby} = $criteriumvalue;
375
376         my $suggestions = &SearchSuggestion({ %$suggestion_ref, archived => $filter_archived });
377         foreach my $suggestion (@$suggestions) {
378             if ($suggestion->{budgetid}){
379                 my $bud = GetBudget( $suggestion->{budgetid} );
380                 $suggestion->{budget_name} = $bud->{budget_name} if $bud;
381             }
382         }
383         push @allsuggestions,{
384                             "suggestiontype"=>$criteriumvalue||"suggest",
385                             "suggestiontypelabel"=>GetCriteriumDesc($criteriumvalue,$displayby)||"",
386                             "suggestionscount"=>scalar(@$suggestions),             
387                             'suggestions_loop'=>$suggestions,
388                             'reasonsloop'     => $reasonsloop,
389                             } if @$suggestions;
390
391         delete $$suggestion_ref{$displayby} unless $definedvalue;
392     }
393
394     $template->param(
395         "displayby"=> $displayby,
396         "notabs"=> $displayby eq "",
397         suggestions       => \@allsuggestions,
398     );
399 }
400
401 $template->param(
402     "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) )
403   for qw(managedby suggestedby acceptedby lastmodificationby);
404
405 $template->param(
406     %$suggestion_ref,
407     filter_archived => $filter_archived,
408     "op"             =>$op,
409 );
410
411 if(defined($returnsuggested) and $returnsuggested ne "noone")
412 {
413     print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions");
414 }
415
416 $template->param(
417     branchfilter => $branchfilter,
418 );
419
420 $template->param( returnsuggestedby => $returnsuggestedby );
421
422 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
423 $template->param(patron_reason_loop=>$patron_reason_loop);
424
425 # Budgets for filtering
426 my $budgets = GetBudgets;
427 my @budgets_loop;
428 foreach my $budget ( @{$budgets} ) {
429     next unless (CanUserUseBudget($borrowernumber, $budget, $userflags));
430
431     ## Please see file perltidy.ERR
432     $budget->{'selected'} = 1
433         if ($$suggestion_ref{'budgetid'}
434         && $budget->{'budget_id'} eq $$suggestion_ref{'budgetid'});
435
436     push @budgets_loop, $budget;
437 }
438 $template->param( budgetsloop => \@budgets_loop);
439
440 # Budgets for suggestion add or edition
441 my $sugg_budget_loop = [];
442 my $sugg_budgets     = GetBudgetHierarchy();
443 foreach my $r ( @{$sugg_budgets} ) {
444     next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) );
445     my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0;
446     push @{$sugg_budget_loop},
447       {
448         b_id     => $r->{budget_id},
449         b_txt    => $r->{budget_name},
450         b_active => $r->{budget_period_active},
451         selected => $selected,
452       };
453 }
454 @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop};
455 $template->param( sugg_budgets => $sugg_budget_loop);
456
457 if( $suggestion_ref->{STATUS} ) {
458     $template->param(
459         "statusselected_".$suggestion_ref->{STATUS} => 1,
460         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
461     );
462 }
463
464 my $currencies = Koha::Acquisition::Currencies->search;
465 $template->param(
466     currencies   => $currencies,
467     suggestion   => $suggestion_ref,
468     price        => sprintf("%.2f", $$suggestion_ref{'price'}||0),
469     total            => sprintf("%.2f", $$suggestion_ref{'total'}||0),
470 );
471
472 # lists of distinct values (without empty) for filters
473 my %hashlists;
474 foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) {
475     my $values_list;
476     $values_list = GetDistinctValues( "suggestions." . $field );
477     my @codes_list = map {
478         {   'code' => $$_{'value'},
479             'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'},
480             'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0,
481         }
482     } grep {
483         $$_{'value'}
484     } @$values_list;
485     $hashlists{ lc($field) . "_loop" } = \@codes_list;
486 }
487
488 $template->param(
489     %hashlists,
490     borrowernumber           => ($input->param('borrowernumber') // undef),
491     SuggestionStatuses       => GetAuthorisedValues('SUGGEST_STATUS'),
492 );
493 output_html_with_http_headers $input, $cookie, $template->output;
494
495 sub redirect_with_params {
496     my ( $input ) = @_;
497     my $params = '';
498     foreach my $key (
499         qw(
500         displayby branchcode title author isbn publishercode copyrightdate
501         collectiontitle suggestedby suggesteddate_from suggesteddate_to
502         manageddate_from manageddate_to accepteddate_from
503         accepteddate_to budgetid filter_archived
504         )
505       )
506     {
507         $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&'
508           if defined($input->param($key));
509     }
510     print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params");
511 }