Bug 30230: (QA follow-up) Add unit tests for API definition change
[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 );
40 use Koha::Database::Columns;
41 use Koha::AuthorisedValues;
42 use Koha::BiblioFrameworks;
43 use Koha::ClassSources;
44 use Koha::Items;
45
46 use List::MoreUtils qw( none );
47
48 my $minlocation=$input->param('minlocation') || '';
49 my $maxlocation=$input->param('maxlocation');
50 my $class_source=$input->param('class_source');
51 $maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation );
52 my $location=$input->param('location') || '';
53 my $ignoreissued=$input->param('ignoreissued');
54 my $ignore_waiting_holds = $input->param('ignore_waiting_holds');
55 my $datelastseen = $input->param('datelastseen'); # last inventory date
56 my $branchcode = $input->param('branchcode') || '';
57 my $branch     = $input->param('branch');
58 my $op         = $input->param('op');
59 my $compareinv2barcd = $input->param('compareinv2barcd');
60 my $dont_checkin = $input->param('dont_checkin');
61 my $out_of_order = $input->param('out_of_order');
62 my $ccode = $input->param('ccode');
63
64 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
65     {   template_name   => "tools/inventory.tt",
66         query           => $input,
67         type            => "intranet",
68         flagsrequired   => { tools => 'inventory' },
69     }
70 );
71
72 my @authorised_value_list;
73 my $authorisedvalue_categories = '';
74
75 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
76 unshift @$frameworks, { frameworkcode => '' };
77
78 my @collections = ();
79 my @collection_codes = ();
80
81 for my $fwk ( @$frameworks ){
82   my $fwkcode = $fwk->{frameworkcode};
83   my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
84   my $authcode = $mss->count ? $mss->next->authorised_value : undef;
85     if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
86       $authorisedvalue_categories.="$authcode ";
87       my $data=GetAuthorisedValues($authcode);
88       foreach my $value (@$data){
89         $value->{selected}=1 if ($value->{authorised_value} eq ($location));
90       }
91       push @authorised_value_list,@$data;
92     }
93 }
94
95 my $statuses = [];
96 my @notforloans;
97 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
98     my $hash = {};
99     $hash->{fieldname} = $statfield;
100     my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
101     $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
102     if ($hash->{authcode}){
103         my $arr = GetAuthorisedValues($hash->{authcode});
104         if ( $statfield eq 'items.notforloan') {
105             # Add notforloan == 0 to the list of possible notforloan statuses
106             # The lib value is replaced in the template
107             push @$arr, { authorised_value => 0, id => 'stat0' , lib => '__IGNORE__' } if ! grep { $_->{authorised_value} eq '0' } @$arr;
108             @notforloans = map { $_->{'authorised_value'} } @$arr;
109         }
110         $hash->{values} = $arr;
111         push @$statuses, $hash;
112     }
113 }
114
115 $template->param( statuses => $statuses );
116 my $staton = {}; #authorized values that are ticked
117 for my $authvfield (@$statuses) {
118     $staton->{$authvfield->{fieldname}} = [];
119     for my $authval (@{$authvfield->{values}}){
120         if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
121             push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
122         }
123     }
124 }
125
126 # if there's a list of not for loans types selected use it rather than
127 # the full set.
128 @notforloans = @{$staton->{'items.notforloan'}} if defined $staton->{'items.notforloan'} and scalar @{$staton->{'items.notforloan'}} > 0;
129
130 my @class_sources = Koha::ClassSources->search({ used => 1 })->as_list;
131 my $pref_class = C4::Context->preference("DefaultClassificationSource");
132
133 my @itemtypes = Koha::ItemTypes->search->as_list;
134 my @selected_itemtypes;
135 foreach my $itemtype ( @itemtypes ) {
136     if ( defined $input->param('itemtype-' . $itemtype->itemtype) ) {
137         push @selected_itemtypes, "'" . $itemtype->itemtype . "'";
138     }
139 }
140
141 $template->param(
142     authorised_values        => \@authorised_value_list,
143     today                    => dt_from_string,
144     minlocation              => $minlocation,
145     maxlocation              => $maxlocation,
146     location                 => $location,
147     ignoreissued             => $ignoreissued,
148     branchcode               => $branchcode,
149     branch                   => $branch,
150     datelastseen             => $datelastseen,
151     compareinv2barcd         => $compareinv2barcd,
152     uploadedbarcodesflag     => ($uploadbarcodes || $barcodelist) ? 1 : 0,
153     ignore_waiting_holds     => $ignore_waiting_holds,
154     class_sources            => \@class_sources,
155     pref_class               => $pref_class,
156     itemtypes                => \@itemtypes,
157     ccode                    => $ccode,
158 );
159
160 # Walk through uploaded barcodes, report errors, mark as seen, check in
161 my $results = {};
162 my @scanned_items;
163 my @errorloop;
164 my $moddatecount = 0;
165 if ( ($uploadbarcodes && length($uploadbarcodes) > 0) || ($barcodelist && length($barcodelist) > 0) ) {
166     my $dbh = C4::Context->dbh;
167     my $date = $input->param('setdate');
168     my $date_dt = dt_from_string($date);
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/, scalar $input->param('barcodelist') );
187         $uploadbarcodes = $barcodelist;
188     }
189     for my $barcode (@uploadedbarcodes) {
190         next unless $barcode;
191
192         $barcode = barcodedecode($barcode);
193
194         ++$lines_read;
195         if (length($barcode)>$barcode_size) {
196             $err_length += 1;
197         }
198         my $check_barcode = $barcode;
199         $check_barcode =~ s/\p{Print}//g;
200         if (length($check_barcode)>0) { # Only printable unicode characters allowed.
201             $err_data += 1;
202         }
203         next if length($barcode)>$barcode_size;
204         next if ( length($check_barcode)>0 );
205         push @barcodes,$barcode;
206     }
207     $template->param( LinesRead => $lines_read );
208     if (! @barcodes) {
209         push @errorloop, {'barcode'=>'No valid barcodes!'};
210         $op=''; # force the initial inventory screen again.
211     }
212     else {
213         $template->param( err_length => $err_length,
214                           err_data   => $err_data );
215     }
216     my @items = Koha::Items->search( { barcode => { -in => \@barcodes } } )->as_list;
217     my %items = map { $_->barcode => $_ } @items;
218     foreach my $barcode (@barcodes) {
219         my $item = $items{ $barcode };
220         if ( $item ) {
221             if ( $item->withdrawn ) {
222                 push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
223                 next;
224             }
225             # Modify date last seen for scanned items, remove lost status
226             $item->set({ itemlost => 0, datelastseen => $date_dt })->store;
227             my $item_unblessed = $item->unblessed;
228             $moddatecount++;
229             unless ( $dont_checkin ) {
230                 if ( $item->onloan ){
231                     #FIXME Is this correct? Shouldn't the item be checked in at the branch we are signed in at?
232                     my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $item->homebranch);
233                     if( $doreturn ) {
234                         $item_unblessed->{onloan} = undef;
235                         $item_unblessed->{datelastseen} = dt_from_string;
236                     } else {
237                         push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
238                     }
239                 }
240             }
241             push @scanned_items, $item_unblessed;
242         } else {
243             push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
244         }
245     }
246     $template->param( date => $date );
247     $template->param( errorloop => \@errorloop ) if (@errorloop);
248 }
249
250 # Build inventorylist: used as result list when you do not pass barcodes
251 # This list is also used when you want to compare with barcodes
252 my ( $inventorylist, $rightplacelist );
253 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
254     ( $inventorylist ) = GetItemsForInventory({
255       minlocation  => $minlocation,
256       maxlocation  => $maxlocation,
257       class_source => $class_source,
258       location     => $location,
259       ignoreissued => $ignoreissued,
260       datelastseen => $datelastseen,
261       branchcode   => $branchcode,
262       branch       => $branch,
263       offset       => 0,
264       statushash   => $staton,
265       ccode        => $ccode,
266       ignore_waiting_holds => $ignore_waiting_holds,
267       itemtypes    => \@selected_itemtypes,
268     });
269 }
270 # Build rightplacelist used to check if a scanned item is in the right place.
271 if( @scanned_items ) {
272     # For the items that may be marked as "wrong place", we only check the location (callnumbers, location, ccode and branch)
273     ( $rightplacelist ) = GetItemsForInventory({
274       minlocation  => $minlocation,
275       maxlocation  => $maxlocation,
276       class_source => $class_source,
277       location     => $location,
278       ignoreissued => undef,
279       datelastseen => undef,
280       branchcode   => $branchcode,
281       branch       => $branch,
282       offset       => 0,
283       statushash   => undef,
284       ignore_waiting_holds => $ignore_waiting_holds,
285       itemtypes    => \@selected_itemtypes,
286       ccode        => $ccode,
287     });
288     # Convert the structure to a hash on barcode
289     $rightplacelist = {
290         map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
291     };
292
293 }
294
295 # Report scanned items that are on the wrong place, or have a wrong notforloan
296 # status, or are still checked out.
297 for ( my $i = 0; $i < @scanned_items; $i++ ) {
298
299     my $item = $scanned_items[$i];
300
301     $item->{notforloancode} = $item->{notforloan}; # save for later use
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 = Koha::Database::Columns->columns;
383     my @translated_keys;
384     for my $key (qw / biblioitems.title    biblio.author
385                       items.barcode        items.itemnumber
386                       items.homebranch     items.location   items.ccode
387                       items.itemcallnumber items.notforloan
388                       items.itemlost       items.damaged
389                       items.withdrawn      items.stocknumber
390                       / ) {
391         my ( $table, $column ) = split '\.', $key;
392         push @translated_keys, NormalizeString($columns->{$table}->{$column} // '');
393     }
394     push @translated_keys, 'Problem' if $uploadbarcodes;
395
396     $csv->combine(@translated_keys);
397     print $csv->string, "\n";
398
399     my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
400     for my $item ( @$loop ) {
401         my @line;
402         for my $key (@keys) {
403             push @line, $item->{$key};
404         }
405         my $errstr = '';
406         foreach my $key ( keys %{$item->{problems}} ) {
407             if( $key eq 'wrongplace' ) {
408                 $errstr .= "wrong place,";
409             } elsif( $key eq 'changestatus' ) {
410                 $errstr .= "unselected notforloan status $item->{notforloan},";
411             } elsif( $key eq 'not_scanned' ) {
412                 $errstr .= "missing,";
413             } elsif( $key eq 'no_barcode' ) {
414                 $errstr .= "no barcode,";
415             } elsif( $key eq 'checkedout' ) {
416                 $errstr .= "checked out,";
417             } elsif( $key eq 'out_of_order' ) {
418                 $errstr .= "shelved out of order,";
419             }
420         }
421         $errstr =~ s/,$//;
422         push @line, $errstr;
423         $csv->combine(@line);
424         print $csv->string, "\n";
425     }
426     # Adding not found barcodes
427     foreach my $error (@errorloop) {
428         my @line;
429         if ($error->{'ERR_BARCODE'}) {
430             push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
431             push @line, "barcode not found";
432             $csv->combine(@line);
433             print $csv->string, "\n";
434         }
435     }
436     exit;
437 }
438
439 output_html_with_http_headers $input, $cookie, $template->output;
440
441 sub additemtoresults {
442     my ( $item, $results ) = @_;
443     my $itemno = $item->{itemnumber};
444
445     my $fc = $item->{'frameworkcode'} || '';
446
447     # Populating with authorised values description
448     foreach my $field (qw/ location notforloan itemlost damaged withdrawn /) {
449         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
450             { frameworkcode => $fc, kohafield => "items.$field", authorised_value => $item->{$field} } );
451         if ( $av and defined $item->{$field} and defined $av->{lib} ) {
452             $item->{$field} = $av->{lib};
453         }
454     }
455
456     # since the script appends to $item, we can just overwrite the hash entry
457     $results->{$itemno} = $item;
458 }