3 # Copyright 2000-2009 Biblibre S.A
4 # John Soros <john.soros@biblibre.com>
6 # This file is part of Koha.
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.
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.
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>.
23 #need to open cgi and get the fh before anything else opens a new cgi context (see C4::Auth)
26 my $uploadbarcodes = $input->param('uploadbarcodes');
27 my $barcodelist = $input->param('barcodelist');
29 use C4::Auth qw( get_template_and_user );
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 );
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;
46 use List::MoreUtils qw( none );
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');
64 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
65 { template_name => "tools/inventory.tt",
68 flagsrequired => { tools => 'inventory' },
72 my @authorised_value_list;
73 my $authorisedvalue_categories = '';
75 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
76 unshift @$frameworks, { frameworkcode => '' };
79 my @collection_codes = ();
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));
91 push @authorised_value_list,@$data;
97 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
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;
110 $hash->{values} = $arr;
111 push @$statuses, $hash;
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};
126 # if there's a list of not for loans types selected use it rather than
128 @notforloans = @{$staton->{'items.notforloan'}} if defined $staton->{'items.notforloan'} and scalar @{$staton->{'items.notforloan'}} > 0;
130 my @class_sources = Koha::ClassSources->search({ used => 1 })->as_list;
131 my $pref_class = C4::Context->preference("DefaultClassificationSource");
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 . "'";
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,
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,
160 # Walk through uploaded barcodes, report errors, mark as seen, check in
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);
171 my @uploadedbarcodes;
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};
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 );
186 push @uploadedbarcodes, split(/\s\n/, scalar $input->param('barcodelist') );
187 $uploadbarcodes = $barcodelist;
189 for my $barcode (@uploadedbarcodes) {
190 next unless $barcode;
192 $barcode = barcodedecode($barcode);
195 if (length($barcode)>$barcode_size) {
198 my $check_barcode = $barcode;
199 $check_barcode =~ s/\p{Print}//g;
200 if (length($check_barcode)>0) { # Only printable unicode characters allowed.
203 next if length($barcode)>$barcode_size;
204 next if ( length($check_barcode)>0 );
205 push @barcodes,$barcode;
207 $template->param( LinesRead => $lines_read );
209 push @errorloop, {'barcode'=>'No valid barcodes!'};
210 $op=''; # force the initial inventory screen again.
213 $template->param( err_length => $err_length,
214 err_data => $err_data );
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 };
221 if ( $item->withdrawn ) {
222 push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
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;
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);
234 $item_unblessed->{onloan} = undef;
235 $item_unblessed->{datelastseen} = dt_from_string;
237 push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
241 push @scanned_items, $item_unblessed;
243 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
246 $template->param( date => $date );
247 $template->param( errorloop => \@errorloop ) if (@errorloop);
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,
264 statushash => $staton,
266 ignore_waiting_holds => $ignore_waiting_holds,
267 itemtypes => \@selected_itemtypes,
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,
284 ignore_waiting_holds => $ignore_waiting_holds,
285 itemtypes => \@selected_itemtypes,
288 # Convert the structure to a hash on barcode
290 map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
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++ ) {
299 my $item = $scanned_items[$i];
301 $item->{notforloancode} = $item->{notforloan}; # save for later use
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 );
309 # Check for items shelved out of order
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 );
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 );
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 );
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};
345 $item->{problems}->{no_barcode} = 1;
346 } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
349 $item->{problems}->{not_scanned} = 1;
351 additemtoresults( $item, $results );
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;
366 moddatecount => $moddatecount,
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(
379 -attachment => 'inventory.csv',
382 my $columns = Koha::Database::Columns->columns;
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
391 my ( $table, $column ) = split '\.', $key;
392 push @translated_keys, NormalizeString($columns->{$table}->{$column} // '');
394 push @translated_keys, 'Problem' if $uploadbarcodes;
396 $csv->combine(@translated_keys);
397 print $csv->string, "\n";
399 my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
400 for my $item ( @$loop ) {
402 for my $key (@keys) {
403 push @line, $item->{$key};
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,";
423 $csv->combine(@line);
424 print $csv->string, "\n";
426 # Adding not found barcodes
427 foreach my $error (@errorloop) {
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";
439 output_html_with_http_headers $input, $cookie, $template->output;
441 sub additemtoresults {
442 my ( $item, $results ) = @_;
443 my $itemno = $item->{itemnumber};
445 my $fc = $item->{'frameworkcode'} || '';
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};
456 # since the script appends to $item, we can just overwrite the hash entry
457 $results->{$itemno} = $item;