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