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