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);
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);
176 my @uploadedbarcodes;
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};
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 );
191 push @uploadedbarcodes, split(/\s\n/, scalar $input->param('barcodelist') );
192 $uploadbarcodes = $barcodelist;
194 for my $barcode (@uploadedbarcodes) {
195 next unless $barcode;
197 $barcode = barcodedecode($barcode);
200 if (length($barcode)>$barcode_size) {
203 my $check_barcode = $barcode;
204 $check_barcode =~ s/\p{Print}//g;
205 if (length($check_barcode)>0) { # Only printable unicode characters allowed.
208 next if length($barcode)>$barcode_size;
209 next if ( length($check_barcode)>0 );
210 push @barcodes,$barcode;
212 $template->param( LinesRead => $lines_read );
214 push @errorloop, {'barcode'=>'No valid barcodes!'};
215 $op=''; # force the initial inventory screen again.
218 $template->param( err_length => $err_length,
219 err_data => $err_data );
221 foreach my $barcode (@barcodes) {
222 if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
223 push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
225 my $item = Koha::Items->find({barcode => $barcode});
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;
231 unless ( $dont_checkin ) {
232 $qonloan->execute($barcode);
234 my $data = $qonloan->fetchrow_hashref;
235 my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
237 $item_unblessed->{onloan} = undef;
238 $item_unblessed->{datelastseen} = dt_from_string;
240 push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
244 push @scanned_items, $item_unblessed;
246 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
250 $template->param( date => $date );
251 $template->param( errorloop => \@errorloop ) if (@errorloop);
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,
268 statushash => $staton,
270 ignore_waiting_holds => $ignore_waiting_holds,
271 itemtypes => \@selected_itemtypes,
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,
288 ignore_waiting_holds => $ignore_waiting_holds,
289 itemtypes => \@selected_itemtypes,
292 # Convert the structure to a hash on barcode
294 map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
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++ ) {
303 my $item = $scanned_items[$i];
305 $item->{notforloancode} = $item->{notforloan}; # save for later use
306 my $fc = $item->{'frameworkcode'} || '';
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};
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 );
323 # Check for items shelved out of order
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 );
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 );
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 );
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};
359 $item->{problems}->{no_barcode} = 1;
360 } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
363 $item->{problems}->{not_scanned} = 1;
365 additemtoresults( $item, $results );
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;
380 moddatecount => $moddatecount,
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(
393 -attachment => 'inventory.csv',
396 my $columns = Koha::Database::Columns->columns;
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
405 my ( $table, $column ) = split '\.', $key;
406 push @translated_keys, NormalizeString($columns->{$table}->{$column} // '');
408 push @translated_keys, 'problem' if $uploadbarcodes;
410 $csv->combine(@translated_keys);
411 print $csv->string, "\n";
413 my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
414 for my $item ( @$loop ) {
416 for my $key (@keys) {
417 push @line, $item->{$key};
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,";
435 $csv->combine(@line);
436 print $csv->string, "\n";
438 # Adding not found barcodes
439 foreach my $error (@errorloop) {
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";
451 output_html_with_http_headers $input, $cookie, $template->output;
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;