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