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