Bug 14973: Check existing biblio when submitting a purchase suggestion (opac side)
[koha.git] / opac / opac-suggestions.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20
21 use CGI qw ( -utf8 );
22 use Encode qw( encode );
23 use C4::Auth;    # get_template_and_user
24 use C4::Members;
25 use C4::Koha;
26 use C4::Output;
27 use C4::Suggestions;
28 use C4::Koha;
29 use C4::Scrubber;
30 use C4::Search qw( FindDuplicate );
31
32 use Koha::AuthorisedValues;
33 use Koha::Libraries;
34 use Koha::Patrons;
35
36 use Koha::DateUtils qw( dt_from_string );
37
38 my $input           = new CGI;
39 my $op              = $input->param('op');
40 my $suggestion      = $input->Vars;
41 my $negcaptcha      = $input->param('negcap');
42 my $suggested_by_anyone = $input->param('suggested_by_anyone') || 0;
43 my $need_confirm    = 0;
44
45 # If a spambot accidentally populates the 'negcap' field in the sugesstions form, then silently skip and return.
46 if ($negcaptcha ) {
47     print $input->redirect("/cgi-bin/koha/opac-suggestions.pl");
48     exit;
49 } else {
50     # don't pass 'negcap' column to DB, else DBI::Class will error
51     # DBIx::Class::Row::store_column(): No such column 'negcap' on Koha::Schema::Result::Suggestion at  Koha/C4/Suggestions.pm
52     delete $suggestion->{negcap};
53 }
54
55 #If suggestions are turned off we redirect to 404 error. This will also redirect guest suggestions
56 if ( ! C4::Context->preference('suggestion') ) {
57     print $input->redirect("/cgi-bin/koha/errors/404.pl");
58     exit;
59 }
60
61 delete $suggestion->{$_} foreach qw<op suggested_by_anyone confirm>;
62 $op = 'else' unless $op;
63
64 my ( $template, $borrowernumber, $cookie, @messages );
65 my $deleted = $input->param('deleted');
66 my $submitted = $input->param('submitted');
67
68 if ( C4::Context->preference("AnonSuggestions") or ( C4::Context->preference("OPACViewOthersSuggestions") and $op eq 'else' ) ) {
69     ( $template, $borrowernumber, $cookie ) = get_template_and_user(
70         {
71             template_name   => "opac-suggestions.tt",
72             query           => $input,
73             type            => "opac",
74             authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
75         }
76     );
77 }
78 else {
79     ( $template, $borrowernumber, $cookie ) = get_template_and_user(
80         {
81             template_name   => "opac-suggestions.tt",
82             query           => $input,
83             type            => "opac",
84             authnotrequired => 0,
85         }
86     );
87 }
88
89 if ( $op eq 'else' ) {
90     if ( C4::Context->preference("OPACViewOthersSuggestions") ) {
91         if ( $borrowernumber ) {
92             # A logged in user is able to see suggestions from others
93             $suggestion->{suggestedby} = $suggested_by_anyone
94                 ? undef
95                 : $borrowernumber;
96         }
97         else {
98             # Non logged in user is able to see all suggestions
99             $suggestion->{suggestedby} = undef;
100         }
101     }
102     else {
103         if ( $borrowernumber ) {
104             $suggestion->{suggestedby} = $borrowernumber;
105         }
106         else {
107             $suggestion->{suggestedby} = -1;
108         }
109     }
110 } else {
111     if ( $borrowernumber ) {
112         $suggestion->{suggestedby} = $borrowernumber;
113     }
114     else {
115         $suggestion->{suggestedby} = C4::Context->preference("AnonymousPatron");
116     }
117 }
118
119 if ( $op eq "add_validate" ) {
120     $op = 'add_confirm';
121     my $biblio = MarcRecordFromNewSuggestion($suggestion);
122     if ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) {
123         push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle };
124         $need_confirm = 1;
125         $op = 'add';
126     }
127 }
128
129 my $patrons_pending_suggestions_count = 0;
130 if ( $borrowernumber && C4::Context->preference("MaxOpenSuggestions") ne '' ) {
131     $patrons_pending_suggestions_count = scalar @{ SearchSuggestion( { suggestedby => $borrowernumber, STATUS => 'ASKED' } ) } ;
132 }
133
134 my $suggestions_loop = &SearchSuggestion($suggestion);
135 if ( $op eq "add_confirm" ) {
136     if ( C4::Context->preference("MaxOpenSuggestions") ne '' && $patrons_pending_suggestions_count >= C4::Context->preference("MaxOpenSuggestions") ) #only check limit for signed in borrowers
137     {
138         push @messages, { type => 'error', code => 'too_many' };
139     }
140     elsif ( @$suggestions_loop >= 1 ) {
141
142         #some suggestion are answering the request Donot Add
143         for my $suggestion (@$suggestions_loop) {
144             push @messages,
145               {
146                 type => 'error',
147                 code => 'already_exists',
148                 id   => $suggestion->{suggestionid}
149               };
150             last;
151         }
152     }
153     else {
154         my $scrubber = C4::Scrubber->new();
155         foreach my $suggest ( keys %$suggestion ) {
156
157             # Don't know why the encode is needed for Perl v5.10 here
158             $suggestion->{$suggest} = Encode::encode( "utf8",
159                 $scrubber->scrub( $suggestion->{$suggest} ) );
160         }
161         $suggestion->{suggesteddate} = dt_from_string;
162         $suggestion->{branchcode} = $input->param('branchcode') || C4::Context->userenv->{"branch"};
163
164         &NewSuggestion($suggestion);
165         $patrons_pending_suggestions_count++;
166
167         # delete empty fields, to avoid filter in "SearchSuggestion"
168         foreach my $field ( qw( title author publishercode copyrightdate place collectiontitle isbn STATUS ) ) {
169             delete $suggestion->{$field}; #clear search filters (except borrower related) to show all suggestions after placing a new one
170         }
171         $suggestions_loop = &SearchSuggestion($suggestion);
172
173         push @messages, { type => 'info', code => 'success_on_inserted' };
174
175     }
176     $op = 'else';
177 }
178
179 my $suggestions_loop = &SearchSuggestion({suggestedby => $suggestion->{suggestedby}});
180 if ( $op eq "delete_confirm" ) {
181     my @delete_field = $input->multi_param("delete_field");
182     foreach my $delete_field (@delete_field) {
183         &DelSuggestion( $borrowernumber, $delete_field );
184     }
185     $op = 'else';
186     print $input->redirect("/cgi-bin/koha/opac-suggestions.pl?op=else");
187     exit;
188 }
189
190 map{
191     my $s = $_;
192     my $library = Koha::Libraries->find($s->{branchcodesuggestedby});
193     $library ? $s->{branchcodesuggestedby} = $library->branchname : ()
194 } @$suggestions_loop;
195
196 foreach my $suggestion(@$suggestions_loop) {
197     if($suggestion->{'suggestedby'} == $borrowernumber) {
198         $suggestion->{'showcheckbox'} = $borrowernumber;
199     } else {
200         $suggestion->{'showcheckbox'} = 0;
201     }
202     if($suggestion->{'patronreason'}){
203         my $av = Koha::AuthorisedValues->search({ category => 'OPAC_SUG', authorised_value => $suggestion->{patronreason} });
204         $suggestion->{'patronreason'} = $av->count ? $av->next->opac_description : '';
205     }
206 }
207
208 my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG");
209
210 # Is the person allowed to choose their branch
211 if ( C4::Context->preference("AllowPurchaseSuggestionBranchChoice") ) {
212     my $branchcode = $input->param('branchcode') || q{};
213
214     if ( !$branchcode
215         && C4::Context->userenv
216         && C4::Context->userenv->{branch} )
217     {
218         $branchcode = C4::Context->userenv->{branch};
219     }
220
221     $template->param( branchcode => $branchcode );
222 }
223
224 my @mandatoryfields;
225 {
226     last unless ($op eq 'add');
227     my $fldsreq_sp = C4::Context->preference("OPACSuggestionMandatoryFields") || 'title';
228     @mandatoryfields = sort split(/\s*\,\s*/, $fldsreq_sp);
229     foreach (@mandatoryfields) {
230         $template->param( $_."_required" => 1);
231     }
232 }
233
234 $template->param(
235     %$suggestion,
236     suggestions_loop      => $suggestions_loop,
237     patron_reason_loop    => $patron_reason_loop,
238     "op_$op"              => 1,
239     $op                   => 1,
240     messages              => \@messages,
241     suggestionsview       => 1,
242     suggested_by_anyone   => $suggested_by_anyone,
243     patrons_pending_suggestions_count => $patrons_pending_suggestions_count,
244     need_confirm => $need_confirm,
245 );
246
247 output_html_with_http_headers $input, $cookie, $template->output, undef, { force_no_caching => 1 };
248