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