Bug 35285: Unit tests
[koha.git] / virtualshelves / shelves.pl
1 #!/usr/bin/perl
2
3 # Copyright 2015 Koha Team
4 #
5 # This file is part of Koha.
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 use CGI qw ( -utf8 );
22 use C4::Auth qw( get_template_and_user haspermission );
23 use C4::Circulation qw( barcodedecode );
24 use C4::Context;
25 use C4::Koha qw(
26     GetNormalizedEAN
27     GetNormalizedISBN
28     GetNormalizedOCLCNumber
29     GetNormalizedUPC
30 );
31 use C4::Members;
32 use C4::Output qw( pagination_bar output_html_with_http_headers output_and_exit_if_error );
33 use C4::XSLT qw( XSLTParse4Display );
34
35 use Koha::Biblios;
36 use Koha::Biblioitems;
37 use Koha::Items;
38 use Koha::ItemTypes;
39 use Koha::CsvProfiles;
40 use Koha::Patrons;
41 use Koha::Virtualshelves;
42
43 use constant ANYONE    => 2;
44 use constant STAFF     => 3;
45 use constant PERMITTED => 4;
46
47 my $query = CGI->new;
48
49 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
50     {   template_name   => "virtualshelves/shelves.tt",
51         query           => $query,
52         type            => "intranet",
53         flagsrequired   => { catalogue => 1 },
54     }
55 );
56
57 my $op       = $query->param('op')      || 'list';
58 my $referer  = $query->param('referer') || $op;
59 my $public   = $query->param('public') ? 1 : 0;
60 my ( $shelf, $shelfnumber, @messages, $allow_transfer );
61
62 # PART1: Perform a few actions
63 if ( $op eq 'add_form' ) {
64     # Only pass default
65     $shelf = { allow_change_from_owner => 1 };
66 } elsif ( $op eq 'edit_form' ) {
67     $shelfnumber = $query->param('shelfnumber');
68     $shelf       = Koha::Virtualshelves->find($shelfnumber);
69
70     if ( $shelf ) {
71         $public = $shelf->public;
72         my $patron = Koha::Patrons->find( $shelf->owner )->unblessed;
73         $template->param( owner => $patron, );
74         unless ( $shelf->can_be_managed( $loggedinuser ) ) {
75             push @messages, { type => 'alert', code => 'unauthorized_on_update' };
76             $op = 'list';
77         }
78     } else {
79         push @messages, { type => 'alert', code => 'does_not_exist' };
80     }
81 } elsif ( $op eq 'add' ) {
82     output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' });
83     my $allow_changes_from = $query->param('allow_changes_from');
84     eval {
85         $shelf = Koha::Virtualshelf->new(
86             {   shelfname          => scalar $query->param('shelfname'),
87                 sortfield          => scalar $query->param('sortfield'),
88                 public             => $public,
89                 allow_change_from_owner           => $allow_changes_from > 0,
90                 allow_change_from_others          => $allow_changes_from == ANYONE,
91                 allow_change_from_staff           => $allow_changes_from == STAFF,
92                 allow_change_from_permitted_staff => $allow_changes_from == PERMITTED,
93                 owner              => scalar $query->param('owner'),
94             }
95         );
96         $shelf->store;
97         $shelfnumber = $shelf->shelfnumber;
98     };
99     if ($@) {
100         push @messages, { type => 'alert', code => ref($@), msg => $@ };
101     } elsif ( not $shelf ) {
102         push @messages, { type => 'alert', code => 'error_on_insert' };
103
104     } else {
105         push @messages, { type => 'message', code => 'success_on_insert' };
106         $op = 'view';
107     }
108 } elsif ( $op eq 'edit' ) {
109     output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' });
110     $shelfnumber = $query->param('shelfnumber');
111     $shelf       = Koha::Virtualshelves->find($shelfnumber);
112
113     if ( $shelf ) {
114         $op = $referer;
115         my $sortfield = $query->param('sortfield');
116         $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded );
117         if ( $shelf->can_be_managed( $loggedinuser ) ) {
118             $shelf->shelfname( scalar $query->param('shelfname') );
119             $shelf->sortfield( $sortfield );
120             my $allow_changes_from = $query->param('allow_changes_from');
121             $shelf->allow_change_from_owner( $allow_changes_from > 0 );
122             $shelf->allow_change_from_others( $allow_changes_from == ANYONE );
123             $shelf->allow_change_from_staff( $allow_changes_from == STAFF );
124             $shelf->allow_change_from_permitted_staff( $allow_changes_from == PERMITTED );
125             $shelf->public( scalar $query->param('public') );
126             eval { $shelf->store };
127
128             if ($@) {
129                 push @messages, { type => 'alert', code => 'error_on_update' };
130                 $op = 'edit_form';
131             } else {
132                 push @messages, { type => 'message', code => 'success_on_update' };
133             }
134         } else {
135             push @messages, { type => 'alert', code => 'unauthorized_on_update' };
136         }
137     } else {
138         push @messages, { type => 'alert', code => 'does_not_exist' };
139     }
140 } elsif ( $op eq 'delete' ) {
141     output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' });
142     $shelfnumber = $query->param('shelfnumber');
143     $shelf       = Koha::Virtualshelves->find($shelfnumber);
144     if ($shelf) {
145         if ( $shelf->can_be_deleted( $loggedinuser ) ) {
146             eval { $shelf->delete; };
147             if ($@) {
148                 push @messages, { type => 'alert', code => ref($@), msg => $@ };
149             } else {
150                 push @messages, { type => 'message', code => 'success_on_delete' };
151             }
152         } else {
153             push @messages, { type => 'alert', code => 'unauthorized_on_delete' };
154         }
155     } else {
156         push @messages, { type => 'alert', code => 'does_not_exist' };
157     }
158     $op = 'list';
159 } elsif ( $op eq 'add_biblio' ) {
160     output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' });
161     $shelfnumber = $query->param('shelfnumber');
162     $shelf = Koha::Virtualshelves->find($shelfnumber);
163     if ($shelf) {
164         if( my $barcodes = $query->param('barcodes') ) {
165             if ( $shelf->can_biblios_be_added( $loggedinuser ) ) {
166                 my @barcodes = split /\n/, $barcodes; # Entries are effectively passed in as a <cr> separated list
167                 foreach my $barcode (@barcodes){
168                     $barcode = barcodedecode( $barcode ) if $barcode;
169                     next if $barcode eq '';
170                     my $item = Koha::Items->find({barcode => $barcode});
171                     if ( $item ) {
172                         my $added = eval { $shelf->add_biblio( $item->biblionumber, $loggedinuser ); };
173                         if ($@) {
174                             push @messages, { item_barcode => $barcode, type => 'alert', code => ref($@), msg => $@ };
175                         } elsif ( $added ) {
176                             push @messages, { item_barcode => $barcode, type => 'message', code => 'success_on_add_biblio' };
177                         } else {
178                             push @messages, { item_barcode => $barcode, type => 'message', code => 'error_on_add_biblio' };
179                         }
180                     } else {
181                         push @messages, { item_barcode => $barcode, type => 'alert', code => 'item_does_not_exist' };
182                     }
183                 }
184             } else {
185                 push @messages, { type => 'alert', code => 'unauthorized_on_add_biblio' };
186             }
187         }
188         if ( my $biblionumbers = $query->param('biblionumbers') ) {
189             if ( $shelf->can_biblios_be_added( $loggedinuser ) ) {
190                 my @biblionumbers = split /\n/, $biblionumbers;
191                 foreach my $biblionumber (@biblionumbers) {
192                     $biblionumber =~ s/\r$//; # strip any naughty return chars
193                     next if $biblionumber eq '';
194                     my $biblio = Koha::Biblios->find($biblionumber);
195                     if (defined $biblio) {
196                         my $added = eval { $shelf->add_biblio( $biblionumber, $loggedinuser ); };
197                         if ($@) {
198                             push @messages, { bibnum => $biblionumber, type => 'alert', code => ref($@), msg => $@ };
199                         } elsif ( $added ) {
200                             push @messages, { bibnum => $biblionumber, type => 'message', code => 'success_on_add_biblio' };
201                         } else {
202                             push @messages, { bibnum => $biblionumber, type => 'message', code => 'error_on_add_biblio' };
203                         }
204                     } else {
205                         push @messages, { bibnum => $biblionumber, type => 'alert', code => 'item_does_not_exist' };
206                     }
207                 }
208             } else {
209                 push @messages, { type => 'alert', code => 'unauthorized_on_add_biblio' };
210             }
211         }
212     } else {
213         push @messages, { type => 'alert', code => 'does_not_exist' };
214     }
215     $op = $referer;
216 } elsif ( $op eq 'remove_biblios' ) {
217     output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' });
218     $shelfnumber = $query->param('shelfnumber');
219     $shelf = Koha::Virtualshelves->find($shelfnumber);
220     my @biblionumbers = $query->multi_param('biblionumber');
221     if ($shelf) {
222         if ( $shelf->can_biblios_be_removed( $loggedinuser ) ) {
223             my $number_of_biblios_removed = eval {
224                 $shelf->remove_biblios(
225                     {
226                         biblionumbers => \@biblionumbers,
227                         borrowernumber => $loggedinuser,
228                     }
229                 );
230             };
231             if ($@) {
232                 push @messages, { type => 'alert', code => ref($@), msg => $@ };
233             } elsif ( $number_of_biblios_removed ) {
234                 push @messages, { type => 'message', code => 'success_on_remove_biblios' };
235             } else {
236                 push @messages, { type => 'alert', code => 'no_biblio_removed' };
237             }
238         } else {
239             push @messages, { type => 'alert', code => 'unauthorized_on_remove_biblios' };
240         }
241     } else {
242         push @messages, { type => 'alert', code => 'does_not_exist' };
243     }
244     $op = $referer;
245 } elsif ( $op eq 'transfer' ) {
246     $shelfnumber = $query->param('shelfnumber');
247     $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber;
248     my $new_owner = $query->param('new_owner'); # is a borrowernumber
249     my $error_code = $shelf
250         ? $shelf->cannot_be_transferred({ by => $loggedinuser, to => $new_owner, interface => 'intranet' })
251         : 'does_not_exist';
252
253     if( !$new_owner && $error_code eq 'missing_to_parameter' ) {
254         # show form
255     } elsif( $error_code ) {
256         push @messages, { type => 'error', code => $error_code };
257         $op = 'list';
258     } else {
259         $shelf->owner($new_owner)->store;
260         $op = 'list';
261     }
262 }
263
264 # PART2: After a possible action, further prepare form
265 if ( $op eq 'view' ) {
266     $shelfnumber ||= $query->param('shelfnumber');
267     $shelf = Koha::Virtualshelves->find($shelfnumber);
268     if ( $shelf ) {
269         if ( $shelf->can_be_viewed( $loggedinuser ) ) {
270             my $sortfield = $query->param('sortfield') || $shelf->sortfield || 'title';    # Passed in sorting overrides default sorting
271             $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded );
272             my $direction = $query->param('direction') || 'asc';
273             $direction = 'asc' if $direction ne 'asc' and $direction ne 'desc';
274             my ( $rows, $page );
275             unless ( $query->param('print') ) {
276                 $rows = C4::Context->preference('numSearchResults') || 20;
277                 $page = ( $query->param('page') ? $query->param('page') : 1 );
278             }
279
280             my $order_by = $sortfield eq 'itemcallnumber' ? 'items.cn_sort' : $sortfield;
281             my $contents = $shelf->get_contents->search(
282                 {},
283                 {
284                     prefetch => [ { 'biblionumber' => { 'biblioitems' => 'items' } } ],
285                     page     => $page,
286                     rows     => $rows,
287                     order_by => { "-$direction" => $order_by },
288                 }
289             );
290
291             my @items;
292             while ( my $content = $contents->next ) {
293                 my $this_item;
294                 my $biblionumber = $content->biblionumber;
295                 my $biblio       = Koha::Biblios->find($biblionumber);
296                 my $record       = $biblio->metadata->record;
297
298                 $this_item->{XSLTBloc} = XSLTParse4Display(
299                     {
300                         biblionumber => $biblionumber,
301                         record       => $record,
302                         xsl_syspref  => 'XSLTListsDisplay',
303                         fix_amps     => 1,
304                     }
305                 );
306
307                 my $marcflavour = C4::Context->preference("marcflavour");
308                 my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype;
309                 $itemtype = Koha::ItemTypes->find( $itemtype );
310                 $this_item->{title}             = $biblio->title;
311                 $this_item->{subtitle}          = $biblio->subtitle;
312                 $this_item->{medium}            = $biblio->medium;
313                 $this_item->{part_number}       = $biblio->part_number;
314                 $this_item->{part_name}         = $biblio->part_name;
315                 $this_item->{author}            = $biblio->author;
316                 $this_item->{dateadded}         = $content->dateadded;
317                 $this_item->{imageurl}          = $itemtype ? C4::Koha::getitemtypeimagelocation( 'intranet', $itemtype->imageurl ) : q{};
318                 $this_item->{description}       = $itemtype ? $itemtype->description : q{}; #FIXME Should this be translated_description ?
319                 $this_item->{notforloan}        = $itemtype->notforloan if $itemtype;
320                 $this_item->{'coins'}           = $biblio->get_coins;
321                 $this_item->{'normalized_upc'}  = GetNormalizedUPC( $record, $marcflavour );
322                 $this_item->{'normalized_ean'}  = GetNormalizedEAN( $record, $marcflavour );
323                 $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber( $record, $marcflavour );
324                 $this_item->{'normalized_isbn'} = GetNormalizedISBN( undef, $record, $marcflavour );
325
326                 unless ( defined $this_item->{size} ) {
327
328                     #TT has problems with size
329                     $this_item->{size} = q||;
330                 }
331
332                 # Getting items infos for location display
333                 my $items = $biblio->items;
334                 $this_item->{'ITEM_RESULTS'} = $items;
335                 $this_item->{biblionumber} = $biblionumber;
336                 push @items, $this_item;
337             }
338
339             my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
340                 {
341                     borrowernumber => $loggedinuser,
342                     add_allowed    => 1,
343                     public         => 0,
344                 }
345             );
346             my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
347                 {
348                     borrowernumber => $loggedinuser,
349                     add_allowed    => 1,
350                     public         => 1,
351                 }
352             );
353
354             $template->param(
355                 add_to_some_private_shelves => $some_private_shelves,
356                 add_to_some_public_shelves  => $some_public_shelves,
357                 can_manage_shelf   => $shelf->can_be_managed($loggedinuser),
358                 can_remove_shelf   => $shelf->can_be_deleted($loggedinuser),
359                 can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser),
360                 can_add_biblios    => $shelf->can_biblios_be_added($loggedinuser),
361                 sortfield          => $sortfield,
362                 itemsloop          => \@items,
363                 sortfield          => $sortfield,
364                 direction          => $direction,
365             );
366             if ( $page ) {
367                 my $pager = $contents->pager;
368                 $template->param(
369                     pagination_bar => pagination_bar(
370                         q||, $pager->last_page - $pager->first_page + 1,
371                         $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, }
372                     ),
373                 );
374             }
375         } else {
376             push @messages, { type => 'error', code => 'unauthorized_on_view' };
377             undef $shelf;
378         }
379     } else {
380         push @messages, { type => 'alert', code => 'does_not_exist' };
381     }
382 } elsif( $op eq 'list' ) {
383     $allow_transfer = haspermission( C4::Context->userenv->{id}, { lists => 'edit_public_lists' } ) ? 1 : 0;
384         # this check only serves for button display
385 }
386
387 $template->param(
388     op       => $op,
389     referer  => $referer,
390     shelf    => $shelf,
391     messages => \@messages,
392     public   => $public,
393     print    => scalar $query->param('print') || 0,
394     csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' })->as_list ],
395     allow_transfer => $allow_transfer,
396 );
397
398 output_html_with_http_headers $query, $cookie, $template->output;