Bug 16522: (follow-up) MARC display templates and get_marc_host fixes
[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 $strsth  = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
171     my $qonloan = $dbh->prepare($strsth);
172     $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
173     my $qwithdrawn = $dbh->prepare($strsth);
174
175     my @barcodes;
176     my @uploadedbarcodes;
177
178     my $sth = $dbh->column_info(undef,undef,"items","barcode");
179     my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME');
180     my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE};
181     my $err_length=0;
182     my $err_data=0;
183     my $lines_read=0;
184     if ($uploadbarcodes && length($uploadbarcodes) > 0) {
185         binmode($uploadbarcodes, ":encoding(UTF-8)");
186         while (my $barcode=<$uploadbarcodes>) {
187             my $split_chars = C4::Context->preference('BarcodeSeparators');
188             push @uploadedbarcodes, grep { /\S/ } split( /[$split_chars]/, $barcode );
189         }
190     } else {
191         push @uploadedbarcodes, split(/\s\n/, scalar $input->param('barcodelist') );
192         $uploadbarcodes = $barcodelist;
193     }
194     for my $barcode (@uploadedbarcodes) {
195         next unless $barcode;
196
197         $barcode = barcodedecode($barcode);
198
199         ++$lines_read;
200         if (length($barcode)>$barcode_size) {
201             $err_length += 1;
202         }
203         my $check_barcode = $barcode;
204         $check_barcode =~ s/\p{Print}//g;
205         if (length($check_barcode)>0) { # Only printable unicode characters allowed.
206             $err_data += 1;
207         }
208         next if length($barcode)>$barcode_size;
209         next if ( length($check_barcode)>0 );
210         push @barcodes,$barcode;
211     }
212     $template->param( LinesRead => $lines_read );
213     if (! @barcodes) {
214         push @errorloop, {'barcode'=>'No valid barcodes!'};
215         $op=''; # force the initial inventory screen again.
216     }
217     else {
218         $template->param( err_length => $err_length,
219                           err_data   => $err_data );
220     }
221     foreach my $barcode (@barcodes) {
222         if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
223             push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
224         } else {
225             my $item = Koha::Items->find({barcode => $barcode});
226             if ( $item ) {
227                 # Modify date last seen for scanned items, remove lost status
228                 $item->set({ itemlost => 0, datelastseen => $date_dt })->store;
229                 my $item_unblessed = $item->unblessed;
230                 $moddatecount++;
231                 unless ( $dont_checkin ) {
232                     $qonloan->execute($barcode);
233                     if ($qonloan->rows){
234                         my $data = $qonloan->fetchrow_hashref;
235                         my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
236                         if( $doreturn ) {
237                             $item_unblessed->{onloan} = undef;
238                             $item_unblessed->{datelastseen} = dt_from_string;
239                         } else {
240                             push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
241                         }
242                     }
243                 }
244                 push @scanned_items, $item_unblessed;
245             } else {
246                 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
247             }
248         }
249     }
250     $template->param( date => $date );
251     $template->param( errorloop => \@errorloop ) if (@errorloop);
252 }
253
254 # Build inventorylist: used as result list when you do not pass barcodes
255 # This list is also used when you want to compare with barcodes
256 my ( $inventorylist, $rightplacelist );
257 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
258     ( $inventorylist ) = GetItemsForInventory({
259       minlocation  => $minlocation,
260       maxlocation  => $maxlocation,
261       class_source => $class_source,
262       location     => $location,
263       ignoreissued => $ignoreissued,
264       datelastseen => $datelastseen,
265       branchcode   => $branchcode,
266       branch       => $branch,
267       offset       => 0,
268       statushash   => $staton,
269       ccode        => $ccode,
270       ignore_waiting_holds => $ignore_waiting_holds,
271       itemtypes    => \@selected_itemtypes,
272     });
273 }
274 # Build rightplacelist used to check if a scanned item is in the right place.
275 if( @scanned_items ) {
276     # For the items that may be marked as "wrong place", we only check the location (callnumbers, location, ccode and branch)
277     ( $rightplacelist ) = GetItemsForInventory({
278       minlocation  => $minlocation,
279       maxlocation  => $maxlocation,
280       class_source => $class_source,
281       location     => $location,
282       ignoreissued => undef,
283       datelastseen => undef,
284       branchcode   => $branchcode,
285       branch       => $branch,
286       offset       => 0,
287       statushash   => undef,
288       ignore_waiting_holds => $ignore_waiting_holds,
289       itemtypes    => \@selected_itemtypes,
290       ccode        => $ccode,
291     });
292     # Convert the structure to a hash on barcode
293     $rightplacelist = {
294         map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
295     };
296
297 }
298
299 # Report scanned items that are on the wrong place, or have a wrong notforloan
300 # status, or are still checked out.
301 for ( my $i = 0; $i < @scanned_items; $i++ ) {
302
303     my $item = $scanned_items[$i];
304
305     $item->{notforloancode} = $item->{notforloan}; # save for later use
306     my $fc = $item->{'frameworkcode'} || '';
307
308     # Populating with authorised values description
309     foreach my $field (qw/ location notforloan itemlost damaged withdrawn /) {
310         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
311             { frameworkcode => $fc, kohafield => "items.$field", authorised_value => $item->{$field} } );
312         if ( $av and defined $item->{$field} and defined $av->{lib} ) {
313             $item->{$field} = $av->{lib};
314         }
315     }
316
317     # If we have scanned items with a non-matching notforloan value
318     if( none { $item->{'notforloancode'} eq $_ } @notforloans ) {
319         $item->{problems}->{changestatus} = 1;
320         additemtoresults( $item, $results );
321     }
322
323     # Check for items shelved out of order
324     if ($out_of_order) {
325         unless ( $i == 0 ) {
326             my $previous_item = $scanned_items[ $i - 1 ];
327             if ( $previous_item && $item->{cn_sort} lt $previous_item->{cn_sort} ) {
328                 $item->{problems}->{out_of_order} = 1;
329                 additemtoresults( $item, $results );
330             }
331         }
332         unless ( $i == scalar(@scanned_items) ) {
333             my $next_item = $scanned_items[ $i + 1 ];
334             if ( $next_item && $item->{cn_sort} gt $next_item->{cn_sort} ) {
335                 $item->{problems}->{out_of_order} = 1;
336                 additemtoresults( $item, $results );
337             }
338         }
339     }
340
341     # Report an item that is checked out (unusual!) or wrongly placed
342     if( $item->{onloan} ) {
343         $item->{problems}->{checkedout} = 1;
344         additemtoresults( $item, $results );
345         next; # do not modify item
346     } elsif( !exists $rightplacelist->{ $item->{barcode} } ) {
347         $item->{problems}->{wrongplace} = 1;
348         additemtoresults( $item, $results );
349     }
350 }
351
352 # Compare barcodes with inventory list, report no_barcode and not_scanned.
353 # not_scanned can be interpreted as missing
354 if ( $compareinv2barcd ) {
355     my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
356     for my $item ( @$inventorylist ) {
357         my $barcode = $item->{barcode};
358         if( !$barcode ) {
359             $item->{problems}->{no_barcode} = 1;
360         } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
361             next;
362         } else {
363             $item->{problems}->{not_scanned} = 1;
364         }
365         additemtoresults( $item, $results );
366     }
367 }
368
369 # Construct final results, add biblio information
370 my $loop = $uploadbarcodes
371     ? [ map { $results->{$_} } keys %$results ]
372     : $inventorylist // [];
373 for my $item ( @$loop ) {
374     my $biblio = Koha::Biblios->find( $item->{biblionumber} );
375     $item->{title} = $biblio->title;
376     $item->{author} = $biblio->author;
377 }
378
379 $template->param(
380     moddatecount => $moddatecount,
381     loop         => $loop,
382     op           => $op,
383 );
384
385 # Export to csv
386 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
387     eval {use Text::CSV ();};
388     my $csv = Text::CSV->new or
389             die Text::CSV->error_diag ();
390     binmode STDOUT, ":encoding(UTF-8)";
391     print $input->header(
392         -type       => 'text/csv',
393         -attachment => 'inventory.csv',
394     );
395
396     my $columns = Koha::Database::Columns->columns;
397     my @translated_keys;
398     for my $key (qw / biblioitems.title    biblio.author
399                       items.barcode        items.itemnumber
400                       items.homebranch     items.location   items.ccode
401                       items.itemcallnumber items.notforloan
402                       items.itemlost       items.damaged
403                       items.withdrawn      items.stocknumber
404                       / ) {
405         my ( $table, $column ) = split '\.', $key;
406         push @translated_keys, NormalizeString($columns->{$table}->{$column} // '');
407     }
408     push @translated_keys, 'problem' if $uploadbarcodes;
409
410     $csv->combine(@translated_keys);
411     print $csv->string, "\n";
412
413     my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
414     for my $item ( @$loop ) {
415         my @line;
416         for my $key (@keys) {
417             push @line, $item->{$key};
418         }
419         my $errstr = '';
420         foreach my $key ( keys %{$item->{problems}} ) {
421             if( $key eq 'wrongplace' ) {
422                 $errstr .= "wrong place,";
423             } elsif( $key eq 'changestatus' ) {
424                 $errstr .= "unknown notforloan status,";
425             } elsif( $key eq 'not_scanned' ) {
426                 $errstr .= "missing,";
427             } elsif( $key eq 'no_barcode' ) {
428                 $errstr .= "no barcode,";
429             } elsif( $key eq 'checkedout' ) {
430                 $errstr .= "checked out,";
431             }
432         }
433         $errstr =~ s/,$//;
434         push @line, $errstr;
435         $csv->combine(@line);
436         print $csv->string, "\n";
437     }
438     # Adding not found barcodes
439     foreach my $error (@errorloop) {
440         my @line;
441         if ($error->{'ERR_BARCODE'}) {
442             push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
443             push @line, "barcode not found";
444             $csv->combine(@line);
445             print $csv->string, "\n";
446         }
447     }
448     exit;
449 }
450
451 output_html_with_http_headers $input, $cookie, $template->output;
452
453 sub additemtoresults {
454     my ( $item, $results ) = @_;
455     my $itemno = $item->{itemnumber};
456     # since the script appends to $item, we can just overwrite the hash entry
457     $results->{$itemno} = $item;
458 }