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