Bug 28782: Use query param list instead of splitting elements using '/'
[koha.git] / tools / inventory.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2009 Biblibre S.A
4 # John Soros <john.soros@biblibre.com>
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 #need to open cgi and get the fh before anything else opens a new cgi context (see C4::Auth)
24 use CGI qw ( -utf8 );
25 my $input = CGI->new;
26 my $uploadbarcodes = $input->param('uploadbarcodes');
27 my $barcodelist = $input->param('barcodelist');
28
29 use C4::Auth qw( get_template_and_user );
30 use C4::Context;
31 use C4::Output qw( output_html_with_http_headers );
32 use C4::Items qw( GetItemsForInventory );
33 use C4::Koha qw( GetAuthorisedValues );
34 use C4::Circulation qw( barcodedecode AddReturn );
35 use C4::Reports::Guided qw( );
36 use C4::Charset qw( NormalizeString );
37
38 use Koha::Biblios;
39 use Koha::DateUtils qw( dt_from_string output_pref );
40 use Koha::AuthorisedValues;
41 use Koha::BiblioFrameworks;
42 use Koha::ClassSources;
43 use Koha::Items;
44
45 use List::MoreUtils qw( none );
46
47 my $minlocation=$input->param('minlocation') || '';
48 my $maxlocation=$input->param('maxlocation');
49 my $class_source=$input->param('class_source');
50 $maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation );
51 my $location=$input->param('location') || '';
52 my $ignoreissued=$input->param('ignoreissued');
53 my $ignore_waiting_holds = $input->param('ignore_waiting_holds');
54 my $datelastseen = $input->param('datelastseen'); # last inventory date
55 my $branchcode = $input->param('branchcode') || '';
56 my $branch     = $input->param('branch');
57 my $op         = $input->param('op');
58 my $compareinv2barcd = $input->param('compareinv2barcd');
59 my $dont_checkin = $input->param('dont_checkin');
60 my $out_of_order = $input->param('out_of_order');
61
62 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
63     {   template_name   => "tools/inventory.tt",
64         query           => $input,
65         type            => "intranet",
66         flagsrequired   => { tools => 'inventory' },
67     }
68 );
69
70 my @authorised_value_list;
71 my $authorisedvalue_categories = '';
72
73 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
74 unshift @$frameworks, { frameworkcode => '' };
75
76 for my $fwk ( @$frameworks ){
77   my $fwkcode = $fwk->{frameworkcode};
78   my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
79   my $authcode = $mss->count ? $mss->next->authorised_value : undef;
80     if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
81       $authorisedvalue_categories.="$authcode ";
82       my $data=GetAuthorisedValues($authcode);
83       foreach my $value (@$data){
84         $value->{selected}=1 if ($value->{authorised_value} eq ($location));
85       }
86       push @authorised_value_list,@$data;
87     }
88 }
89
90 my $statuses = [];
91 my @notforloans;
92 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
93     my $hash = {};
94     $hash->{fieldname} = $statfield;
95     my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
96     $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
97     if ($hash->{authcode}){
98         my $arr = GetAuthorisedValues($hash->{authcode});
99         if ( $statfield eq 'items.notforloan') {
100             # Add notforloan == 0 to the list of possible notforloan statuses
101             # The lib value is replaced in the template
102             push @$arr, { authorised_value => 0, id => 'stat0' , lib => '__IGNORE__' } if ! grep { $_->{authorised_value} eq '0' } @$arr;
103             @notforloans = map { $_->{'authorised_value'} } @$arr;
104         }
105         $hash->{values} = $arr;
106         push @$statuses, $hash;
107     }
108 }
109
110 $template->param( statuses => $statuses );
111 my $staton = {}; #authorized values that are ticked
112 for my $authvfield (@$statuses) {
113     $staton->{$authvfield->{fieldname}} = [];
114     for my $authval (@{$authvfield->{values}}){
115         if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
116             push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
117         }
118     }
119 }
120
121 # if there's a list of not for loans types selected use it rather than
122 # the full set.
123 @notforloans = @{$staton->{'items.notforloan'}} if defined $staton->{'items.notforloan'} and scalar @{$staton->{'items.notforloan'}} > 0;
124
125 my @class_sources = Koha::ClassSources->search({ used => 1 })->as_list;
126 my $pref_class = C4::Context->preference("DefaultClassificationSource");
127
128 my @itemtypes = Koha::ItemTypes->search->as_list;
129 my @selected_itemtypes;
130 foreach my $itemtype ( @itemtypes ) {
131     if ( defined $input->param('itemtype-' . $itemtype->itemtype) ) {
132         push @selected_itemtypes, "'" . $itemtype->itemtype . "'";
133     }
134 }
135
136 $template->param(
137     authorised_values        => \@authorised_value_list,
138     today                    => dt_from_string,
139     minlocation              => $minlocation,
140     maxlocation              => $maxlocation,
141     location                 => $location,
142     ignoreissued             => $ignoreissued,
143     branchcode               => $branchcode,
144     branch                   => $branch,
145     datelastseen             => $datelastseen,
146     compareinv2barcd         => $compareinv2barcd,
147     uploadedbarcodesflag     => ($uploadbarcodes || $barcodelist) ? 1 : 0,
148     ignore_waiting_holds     => $ignore_waiting_holds,
149     class_sources            => \@class_sources,
150     pref_class               => $pref_class,
151     itemtypes                => \@itemtypes,
152 );
153
154 # Walk through uploaded barcodes, report errors, mark as seen, check in
155 my $results = {};
156 my @scanned_items;
157 my @errorloop;
158 my $moddatecount = 0;
159 if ( ($uploadbarcodes && length($uploadbarcodes) > 0) || ($barcodelist && length($barcodelist) > 0) ) {
160     my $dbh = C4::Context->dbh;
161     my $date = $input->param('setdate');
162     my $date_dt = dt_from_string($date);
163
164     my $strsth  = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
165     my $qonloan = $dbh->prepare($strsth);
166     $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
167     my $qwithdrawn = $dbh->prepare($strsth);
168
169     my @barcodes;
170     my @uploadedbarcodes;
171
172     my $sth = $dbh->column_info(undef,undef,"items","barcode");
173     my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME');
174     my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE};
175     my $err_length=0;
176     my $err_data=0;
177     my $lines_read=0;
178     if ($uploadbarcodes && length($uploadbarcodes) > 0) {
179         binmode($uploadbarcodes, ":encoding(UTF-8)");
180         while (my $barcode=<$uploadbarcodes>) {
181             my $split_chars = C4::Context->preference('BarcodeSeparators');
182             push @uploadedbarcodes, grep { /\S/ } split( /[$split_chars]/, $barcode );
183         }
184     } else {
185         push @uploadedbarcodes, split(/\s\n/, $input->param('barcodelist') );
186         $uploadbarcodes = $barcodelist;
187     }
188     for my $barcode (@uploadedbarcodes) {
189         next unless $barcode;
190
191         $barcode = barcodedecode($barcode);
192
193         ++$lines_read;
194         if (length($barcode)>$barcode_size) {
195             $err_length += 1;
196         }
197         my $check_barcode = $barcode;
198         $check_barcode =~ s/\p{Print}//g;
199         if (length($check_barcode)>0) { # Only printable unicode characters allowed.
200             $err_data += 1;
201         }
202         next if length($barcode)>$barcode_size;
203         next if ( length($check_barcode)>0 );
204         push @barcodes,$barcode;
205     }
206     $template->param( LinesRead => $lines_read );
207     if (! @barcodes) {
208         push @errorloop, {'barcode'=>'No valid barcodes!'};
209         $op=''; # force the initial inventory screen again.
210     }
211     else {
212         $template->param( err_length => $err_length,
213                           err_data   => $err_data );
214     }
215     foreach my $barcode (@barcodes) {
216         if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
217             push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
218         } else {
219             my $item = Koha::Items->find({barcode => $barcode});
220             if ( $item ) {
221                 # Modify date last seen for scanned items, remove lost status
222                 $item->set({ itemlost => 0, datelastseen => $date_dt })->store;
223                 my $item_unblessed = $item->unblessed;
224                 $moddatecount++;
225                 unless ( $dont_checkin ) {
226                     $qonloan->execute($barcode);
227                     if ($qonloan->rows){
228                         my $data = $qonloan->fetchrow_hashref;
229                         my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
230                         if( $doreturn ) {
231                             $item_unblessed->{onloan} = undef;
232                             $item_unblessed->{datelastseen} = dt_from_string;
233                         } else {
234                             push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
235                         }
236                     }
237                 }
238                 push @scanned_items, $item_unblessed;
239             } else {
240                 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
241             }
242         }
243     }
244     $template->param( date => output_pref ( { str => $date, dateformat => 'iso' } ) );
245     $template->param( errorloop => \@errorloop ) if (@errorloop);
246 }
247
248 # Build inventorylist: used as result list when you do not pass barcodes
249 # This list is also used when you want to compare with barcodes
250 my ( $inventorylist, $rightplacelist );
251 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
252     ( $inventorylist ) = GetItemsForInventory({
253       minlocation  => $minlocation,
254       maxlocation  => $maxlocation,
255       class_source => $class_source,
256       location     => $location,
257       ignoreissued => $ignoreissued,
258       datelastseen => $datelastseen,
259       branchcode   => $branchcode,
260       branch       => $branch,
261       offset       => 0,
262       statushash   => $staton,
263       ignore_waiting_holds => $ignore_waiting_holds,
264       itemtypes    => \@selected_itemtypes,
265     });
266 }
267 # Build rightplacelist used to check if a scanned item is in the right place.
268 if( @scanned_items ) {
269     ( $rightplacelist ) = GetItemsForInventory({
270       minlocation  => $minlocation,
271       maxlocation  => $maxlocation,
272       class_source => $class_source,
273       location     => $location,
274       ignoreissued => undef,
275       datelastseen => undef,
276       branchcode   => $branchcode,
277       branch       => $branch,
278       offset       => 0,
279       statushash   => undef,
280       ignore_waiting_holds => $ignore_waiting_holds,
281       itemtypes    => \@selected_itemtypes,
282     });
283     # Convert the structure to a hash on barcode
284     $rightplacelist = {
285         map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
286     };
287 }
288
289 # Report scanned items that are on the wrong place, or have a wrong notforloan
290 # status, or are still checked out.
291 for ( my $i = 0; $i < @scanned_items; $i++ ) {
292
293     my $item = $scanned_items[$i];
294
295     $item->{notforloancode} = $item->{notforloan}; # save for later use
296     my $fc = $item->{'frameworkcode'} || '';
297
298     # Populating with authorised values description
299     foreach my $field (qw/ location notforloan itemlost damaged withdrawn /) {
300         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
301             { frameworkcode => $fc, kohafield => "items.$field", authorised_value => $item->{$field} } );
302         if ( $av and defined $item->{$field} and defined $av->{lib} ) {
303             $item->{$field} = $av->{lib};
304         }
305     }
306
307     # If we have scanned items with a non-matching notforloan value
308     if( none { $item->{'notforloancode'} eq $_ } @notforloans ) {
309         $item->{problems}->{changestatus} = 1;
310         additemtoresults( $item, $results );
311     }
312
313     # Check for items shelved out of order
314     if ($out_of_order) {
315         unless ( $i == 0 ) {
316             my $previous_item = $scanned_items[ $i - 1 ];
317             if ( $previous_item && $item->{cn_sort} lt $previous_item->{cn_sort} ) {
318                 $item->{problems}->{out_of_order} = 1;
319                 additemtoresults( $item, $results );
320             }
321         }
322         unless ( $i == scalar(@scanned_items) ) {
323             my $next_item = $scanned_items[ $i + 1 ];
324             if ( $next_item && $item->{cn_sort} gt $next_item->{cn_sort} ) {
325                 $item->{problems}->{out_of_order} = 1;
326                 additemtoresults( $item, $results );
327             }
328         }
329     }
330
331     # Report an item that is checked out (unusual!) or wrongly placed
332     if( $item->{onloan} ) {
333         $item->{problems}->{checkedout} = 1;
334         additemtoresults( $item, $results );
335         next; # do not modify item
336     } elsif( !exists $rightplacelist->{ $item->{barcode} } ) {
337         $item->{problems}->{wrongplace} = 1;
338         additemtoresults( $item, $results );
339     }
340 }
341
342 # Compare barcodes with inventory list, report no_barcode and not_scanned.
343 # not_scanned can be interpreted as missing
344 if ( $compareinv2barcd ) {
345     my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
346     for my $item ( @$inventorylist ) {
347         my $barcode = $item->{barcode};
348         if( !$barcode ) {
349             $item->{problems}->{no_barcode} = 1;
350         } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
351             next;
352         } else {
353             $item->{problems}->{not_scanned} = 1;
354         }
355         additemtoresults( $item, $results );
356     }
357 }
358
359 # Construct final results, add biblio information
360 my $loop = $uploadbarcodes
361     ? [ map { $results->{$_} } keys %$results ]
362     : $inventorylist // [];
363 for my $item ( @$loop ) {
364     my $biblio = Koha::Biblios->find( $item->{biblionumber} );
365     $item->{title} = $biblio->title;
366     $item->{author} = $biblio->author;
367 }
368
369 $template->param(
370     moddatecount => $moddatecount,
371     loop         => $loop,
372     op           => $op,
373 );
374
375 # Export to csv
376 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
377     eval {use Text::CSV ();};
378     my $csv = Text::CSV->new or
379             die Text::CSV->error_diag ();
380     binmode STDOUT, ":encoding(UTF-8)";
381     print $input->header(
382         -type       => 'text/csv',
383         -attachment => 'inventory.csv',
384     );
385
386     my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
387     foreach my $key ( keys %$columns_def_hashref ) {
388         my $initkey = $key;
389         $key =~ s/[^\.]*\.//;
390         $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
391         $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
392     }
393
394     my @translated_keys;
395     for my $key (qw / biblioitems.title    biblio.author
396                       items.barcode        items.itemnumber
397                       items.homebranch     items.location
398                       items.itemcallnumber items.notforloan
399                       items.itemlost       items.damaged
400                       items.withdrawn      items.stocknumber
401                       / ) {
402        push @translated_keys, $columns_def_hashref->{$key};
403     }
404     push @translated_keys, 'problem' if $uploadbarcodes;
405
406     $csv->combine(@translated_keys);
407     print $csv->string, "\n";
408
409     my @keys = qw/ title author barcode itemnumber homebranch location itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
410     for my $item ( @$loop ) {
411         my @line;
412         for my $key (@keys) {
413             push @line, $item->{$key};
414         }
415         my $errstr = '';
416         foreach my $key ( keys %{$item->{problems}} ) {
417             if( $key eq 'wrongplace' ) {
418                 $errstr .= "wrong place,";
419             } elsif( $key eq 'changestatus' ) {
420                 $errstr .= "unknown notforloan status,";
421             } elsif( $key eq 'not_scanned' ) {
422                 $errstr .= "missing,";
423             } elsif( $key eq 'no_barcode' ) {
424                 $errstr .= "no barcode,";
425             } elsif( $key eq 'checkedout' ) {
426                 $errstr .= "checked out,";
427             }
428         }
429         $errstr =~ s/,$//;
430         push @line, $errstr;
431         $csv->combine(@line);
432         print $csv->string, "\n";
433     }
434     # Adding not found barcodes
435     foreach my $error (@errorloop) {
436         my @line;
437         if ($error->{'ERR_BARCODE'}) {
438             push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
439             push @line, "barcode not found";
440             $csv->combine(@line);
441             print $csv->string, "\n";
442         }
443     }
444     exit;
445 }
446
447 output_html_with_http_headers $input, $cookie, $template->output;
448
449 sub additemtoresults {
450     my ( $item, $results ) = @_;
451     my $itemno = $item->{itemnumber};
452     # since the script appends to $item, we can just overwrite the hash entry
453     $results->{$itemno} = $item;
454 }