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