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 output_pref );
40 use Koha::AuthorisedValues;
41 use Koha::BiblioFrameworks;
42 use Koha::ClassSources;
45 use List::MoreUtils qw( none );
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 my $ccode = $input->param('ccode');
63 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
64 { template_name => "tools/inventory.tt",
67 flagsrequired => { tools => 'inventory' },
71 my @authorised_value_list;
72 my $authorisedvalue_categories = '';
74 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
75 unshift @$frameworks, { frameworkcode => '' };
78 my @collection_codes = ();
80 for my $fwk ( @$frameworks ){
81 my $fwkcode = $fwk->{frameworkcode};
82 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
83 my $authcode = $mss->count ? $mss->next->authorised_value : undef;
84 if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
85 $authorisedvalue_categories.="$authcode ";
86 my $data=GetAuthorisedValues($authcode);
87 foreach my $value (@$data){
88 $value->{selected}=1 if ($value->{authorised_value} eq ($location));
90 push @authorised_value_list,@$data;
96 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
98 $hash->{fieldname} = $statfield;
99 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
100 $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
101 if ($hash->{authcode}){
102 my $arr = GetAuthorisedValues($hash->{authcode});
103 if ( $statfield eq 'items.notforloan') {
104 # Add notforloan == 0 to the list of possible notforloan statuses
105 # The lib value is replaced in the template
106 push @$arr, { authorised_value => 0, id => 'stat0' , lib => '__IGNORE__' } if ! grep { $_->{authorised_value} eq '0' } @$arr;
107 @notforloans = map { $_->{'authorised_value'} } @$arr;
109 $hash->{values} = $arr;
110 push @$statuses, $hash;
114 $template->param( statuses => $statuses );
115 my $staton = {}; #authorized values that are ticked
116 for my $authvfield (@$statuses) {
117 $staton->{$authvfield->{fieldname}} = [];
118 for my $authval (@{$authvfield->{values}}){
119 if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
120 push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
125 # if there's a list of not for loans types selected use it rather than
127 @notforloans = @{$staton->{'items.notforloan'}} if defined $staton->{'items.notforloan'} and scalar @{$staton->{'items.notforloan'}} > 0;
129 my @class_sources = Koha::ClassSources->search({ used => 1 })->as_list;
130 my $pref_class = C4::Context->preference("DefaultClassificationSource");
132 my @itemtypes = Koha::ItemTypes->search->as_list;
133 my @selected_itemtypes;
134 foreach my $itemtype ( @itemtypes ) {
135 if ( defined $input->param('itemtype-' . $itemtype->itemtype) ) {
136 push @selected_itemtypes, "'" . $itemtype->itemtype . "'";
141 authorised_values => \@authorised_value_list,
142 today => dt_from_string,
143 minlocation => $minlocation,
144 maxlocation => $maxlocation,
145 location => $location,
146 ignoreissued => $ignoreissued,
147 branchcode => $branchcode,
149 datelastseen => $datelastseen,
150 compareinv2barcd => $compareinv2barcd,
151 uploadedbarcodesflag => ($uploadbarcodes || $barcodelist) ? 1 : 0,
152 ignore_waiting_holds => $ignore_waiting_holds,
153 class_sources => \@class_sources,
154 pref_class => $pref_class,
155 itemtypes => \@itemtypes,
159 # Walk through uploaded barcodes, report errors, mark as seen, check in
163 my $moddatecount = 0;
164 if ( ($uploadbarcodes && length($uploadbarcodes) > 0) || ($barcodelist && length($barcodelist) > 0) ) {
165 my $dbh = C4::Context->dbh;
166 my $date = $input->param('setdate');
167 my $date_dt = dt_from_string($date);
169 my $strsth = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
170 my $qonloan = $dbh->prepare($strsth);
171 $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
172 my $qwithdrawn = $dbh->prepare($strsth);
175 my @uploadedbarcodes;
177 my $sth = $dbh->column_info(undef,undef,"items","barcode");
178 my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME');
179 my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE};
183 if ($uploadbarcodes && length($uploadbarcodes) > 0) {
184 binmode($uploadbarcodes, ":encoding(UTF-8)");
185 while (my $barcode=<$uploadbarcodes>) {
186 my $split_chars = C4::Context->preference('BarcodeSeparators');
187 push @uploadedbarcodes, grep { /\S/ } split( /[$split_chars]/, $barcode );
190 push @uploadedbarcodes, split(/\s\n/, scalar $input->param('barcodelist') );
191 $uploadbarcodes = $barcodelist;
193 for my $barcode (@uploadedbarcodes) {
194 next unless $barcode;
196 $barcode = barcodedecode($barcode);
199 if (length($barcode)>$barcode_size) {
202 my $check_barcode = $barcode;
203 $check_barcode =~ s/\p{Print}//g;
204 if (length($check_barcode)>0) { # Only printable unicode characters allowed.
207 next if length($barcode)>$barcode_size;
208 next if ( length($check_barcode)>0 );
209 push @barcodes,$barcode;
211 $template->param( LinesRead => $lines_read );
213 push @errorloop, {'barcode'=>'No valid barcodes!'};
214 $op=''; # force the initial inventory screen again.
217 $template->param( err_length => $err_length,
218 err_data => $err_data );
220 foreach my $barcode (@barcodes) {
221 if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
222 push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
224 my $item = Koha::Items->find({barcode => $barcode});
226 # Modify date last seen for scanned items, remove lost status
227 $item->set({ itemlost => 0, datelastseen => $date_dt })->store;
228 my $item_unblessed = $item->unblessed;
230 unless ( $dont_checkin ) {
231 $qonloan->execute($barcode);
233 my $data = $qonloan->fetchrow_hashref;
234 my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
236 $item_unblessed->{onloan} = undef;
237 $item_unblessed->{datelastseen} = dt_from_string;
239 push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
243 push @scanned_items, $item_unblessed;
245 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
249 $template->param( date => output_pref ( { str => $date, dateformat => 'iso' } ) );
250 $template->param( errorloop => \@errorloop ) if (@errorloop);
253 # Build inventorylist: used as result list when you do not pass barcodes
254 # This list is also used when you want to compare with barcodes
255 my ( $inventorylist, $rightplacelist );
256 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
257 ( $inventorylist ) = GetItemsForInventory({
258 minlocation => $minlocation,
259 maxlocation => $maxlocation,
260 class_source => $class_source,
261 location => $location,
262 ignoreissued => $ignoreissued,
263 datelastseen => $datelastseen,
264 branchcode => $branchcode,
267 statushash => $staton,
269 ignore_waiting_holds => $ignore_waiting_holds,
270 itemtypes => \@selected_itemtypes,
273 # Build rightplacelist used to check if a scanned item is in the right place.
274 if( @scanned_items ) {
275 # For the items that may be marked as "wrong place", we only check the location (callnumbers, location, ccode and branch)
276 ( $rightplacelist ) = GetItemsForInventory({
277 minlocation => $minlocation,
278 maxlocation => $maxlocation,
279 class_source => $class_source,
280 location => $location,
281 ignoreissued => undef,
282 datelastseen => undef,
283 branchcode => $branchcode,
287 ignore_waiting_holds => $ignore_waiting_holds,
288 itemtypes => \@selected_itemtypes,
291 # Convert the structure to a hash on barcode
293 map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
298 # Report scanned items that are on the wrong place, or have a wrong notforloan
299 # status, or are still checked out.
300 for ( my $i = 0; $i < @scanned_items; $i++ ) {
302 my $item = $scanned_items[$i];
304 $item->{notforloancode} = $item->{notforloan}; # save for later use
305 my $fc = $item->{'frameworkcode'} || '';
307 # Populating with authorised values description
308 foreach my $field (qw/ location notforloan itemlost damaged withdrawn /) {
309 my $av = Koha::AuthorisedValues->get_description_by_koha_field(
310 { frameworkcode => $fc, kohafield => "items.$field", authorised_value => $item->{$field} } );
311 if ( $av and defined $item->{$field} and defined $av->{lib} ) {
312 $item->{$field} = $av->{lib};
316 # If we have scanned items with a non-matching notforloan value
317 if( none { $item->{'notforloancode'} eq $_ } @notforloans ) {
318 $item->{problems}->{changestatus} = 1;
319 additemtoresults( $item, $results );
322 # Check for items shelved out of order
325 my $previous_item = $scanned_items[ $i - 1 ];
326 if ( $previous_item && $item->{cn_sort} lt $previous_item->{cn_sort} ) {
327 $item->{problems}->{out_of_order} = 1;
328 additemtoresults( $item, $results );
331 unless ( $i == scalar(@scanned_items) ) {
332 my $next_item = $scanned_items[ $i + 1 ];
333 if ( $next_item && $item->{cn_sort} gt $next_item->{cn_sort} ) {
334 $item->{problems}->{out_of_order} = 1;
335 additemtoresults( $item, $results );
340 # Report an item that is checked out (unusual!) or wrongly placed
341 if( $item->{onloan} ) {
342 $item->{problems}->{checkedout} = 1;
343 additemtoresults( $item, $results );
344 next; # do not modify item
345 } elsif( !exists $rightplacelist->{ $item->{barcode} } ) {
346 $item->{problems}->{wrongplace} = 1;
347 additemtoresults( $item, $results );
351 # Compare barcodes with inventory list, report no_barcode and not_scanned.
352 # not_scanned can be interpreted as missing
353 if ( $compareinv2barcd ) {
354 my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
355 for my $item ( @$inventorylist ) {
356 my $barcode = $item->{barcode};
358 $item->{problems}->{no_barcode} = 1;
359 } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
362 $item->{problems}->{not_scanned} = 1;
364 additemtoresults( $item, $results );
368 # Construct final results, add biblio information
369 my $loop = $uploadbarcodes
370 ? [ map { $results->{$_} } keys %$results ]
371 : $inventorylist // [];
372 for my $item ( @$loop ) {
373 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
374 $item->{title} = $biblio->title;
375 $item->{author} = $biblio->author;
379 moddatecount => $moddatecount,
385 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
386 eval {use Text::CSV ();};
387 my $csv = Text::CSV->new or
388 die Text::CSV->error_diag ();
389 binmode STDOUT, ":encoding(UTF-8)";
390 print $input->header(
392 -attachment => 'inventory.csv',
395 my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
396 foreach my $key ( keys %$columns_def_hashref ) {
398 $key =~ s/[^\.]*\.//;
399 $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
400 $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
404 for my $key (qw / biblioitems.title biblio.author
405 items.barcode items.itemnumber
406 items.homebranch items.location items.ccode
407 items.itemcallnumber items.notforloan
408 items.itemlost items.damaged
409 items.withdrawn items.stocknumber
411 push @translated_keys, $columns_def_hashref->{$key};
413 push @translated_keys, 'problem' if $uploadbarcodes;
415 $csv->combine(@translated_keys);
416 print $csv->string, "\n";
418 my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
419 for my $item ( @$loop ) {
421 for my $key (@keys) {
422 push @line, $item->{$key};
425 foreach my $key ( keys %{$item->{problems}} ) {
426 if( $key eq 'wrongplace' ) {
427 $errstr .= "wrong place,";
428 } elsif( $key eq 'changestatus' ) {
429 $errstr .= "unknown notforloan status,";
430 } elsif( $key eq 'not_scanned' ) {
431 $errstr .= "missing,";
432 } elsif( $key eq 'no_barcode' ) {
433 $errstr .= "no barcode,";
434 } elsif( $key eq 'checkedout' ) {
435 $errstr .= "checked out,";
440 $csv->combine(@line);
441 print $csv->string, "\n";
443 # Adding not found barcodes
444 foreach my $error (@errorloop) {
446 if ($error->{'ERR_BARCODE'}) {
447 push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
448 push @line, "barcode not found";
449 $csv->combine(@line);
450 print $csv->string, "\n";
456 output_html_with_http_headers $input, $cookie, $template->output;
458 sub additemtoresults {
459 my ( $item, $results ) = @_;
460 my $itemno = $item->{itemnumber};
461 # since the script appends to $item, we can just overwrite the hash entry
462 $results->{$itemno} = $item;