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');
36 use C4::Reports::Guided; #_get_column_defs
41 use Koha::AuthorisedValues;
42 use Koha::BiblioFrameworks;
43 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');
62 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
63 { template_name => "tools/inventory.tt",
66 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 => '' };
77 for my $fwk ( @$frameworks ){
78 my $fwkcode = $fwk->{frameworkcode};
79 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
80 my $authcode = $mss->count ? $mss->next->authorised_value : undef;
81 if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
82 $authorisedvalue_categories.="$authcode ";
83 my $data=GetAuthorisedValues($authcode);
84 foreach my $value (@$data){
85 $value->{selected}=1 if ($value->{authorised_value} eq ($location));
87 push @authorised_value_list,@$data;
93 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
95 $hash->{fieldname} = $statfield;
96 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
97 $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
98 if ($hash->{authcode}){
99 my $arr = GetAuthorisedValues($hash->{authcode});
100 if ( $statfield eq 'items.notforloan') {
101 # Add notforloan == 0 to the list of possible notforloan statuses
102 # The lib value is replaced in the template
103 push @$arr, { authorised_value => 0, id => 'stat0' , lib => '__IGNORE__' } if ! grep { $_->{authorised_value} eq '0' } @$arr;
104 @notforloans = map { $_->{'authorised_value'} } @$arr;
106 $hash->{values} = $arr;
107 push @$statuses, $hash;
111 $template->param( statuses => $statuses );
112 my $staton = {}; #authorized values that are ticked
113 for my $authvfield (@$statuses) {
114 $staton->{$authvfield->{fieldname}} = [];
115 for my $authval (@{$authvfield->{values}}){
116 if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
117 push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
122 # if there's a list of not for loans types selected use it rather than
124 if ($staton->{'items.notforloan'}) {
125 my @l = @{$staton->{'items.notforloan'}};
126 @notforloans = @l if scalar @l > 0;
129 my @class_sources = Koha::ClassSources->search({ used => 1 });
130 my $pref_class = C4::Context->preference("DefaultClassificationSource");
134 authorised_values => \@authorised_value_list,
135 today => dt_from_string,
136 minlocation => $minlocation,
137 maxlocation => $maxlocation,
138 location => $location,
139 ignoreissued => $ignoreissued,
140 branchcode => $branchcode,
142 datelastseen => $datelastseen,
143 compareinv2barcd => $compareinv2barcd,
144 uploadedbarcodesflag => ($uploadbarcodes || $barcodelist) ? 1 : 0,
145 ignore_waiting_holds => $ignore_waiting_holds,
146 class_sources => \@class_sources,
147 pref_class => $pref_class
150 # Walk through uploaded barcodes, report errors, mark as seen, check in
154 my $moddatecount = 0;
155 if ( ($uploadbarcodes && length($uploadbarcodes) > 0) || ($barcodelist && length($barcodelist) > 0) ) {
156 my $dbh = C4::Context->dbh;
157 my $date = dt_from_string( scalar $input->param('setdate') );
158 $date = output_pref ( { dt => $date, dateformat => 'iso' } );
160 my $strsth = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
161 my $qonloan = $dbh->prepare($strsth);
162 $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
163 my $qwithdrawn = $dbh->prepare($strsth);
166 my @uploadedbarcodes;
168 my $sth = $dbh->column_info(undef,undef,"items","barcode");
169 my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME');
170 my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE};
174 if ($uploadbarcodes && length($uploadbarcodes) > 0) {
175 binmode($uploadbarcodes, ":encoding(UTF-8)");
176 while (my $barcode=<$uploadbarcodes>) {
177 my $split_chars = C4::Context->preference('BarcodeSeparators');
178 push @uploadedbarcodes, grep { /\S/ } split( /[$split_chars]/, $barcode );
181 push @uploadedbarcodes, split(/\s\n/, $input->param('barcodelist') );
182 $uploadbarcodes = $barcodelist;
184 for my $barcode (@uploadedbarcodes) {
185 next unless $barcode;
187 if (length($barcode)>$barcode_size) {
190 my $check_barcode = $barcode;
191 $check_barcode =~ s/\p{Print}//g;
192 if (length($check_barcode)>0) { # Only printable unicode characters allowed.
195 next if length($barcode)>$barcode_size;
196 next if ( length($check_barcode)>0 );
197 push @barcodes,$barcode;
199 $template->param( LinesRead => $lines_read );
201 push @errorloop, {'barcode'=>'No valid barcodes!'};
202 $op=''; # force the initial inventory screen again.
205 $template->param( err_length => $err_length,
206 err_data => $err_data );
208 foreach my $barcode (@barcodes) {
209 if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
210 push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
212 my $item = Koha::Items->find({barcode => $barcode});
214 # Modify date last seen for scanned items, remove lost status
215 $item->set({ itemlost => 0, datelastseen => $date })->store;
216 my $item_unblessed = $item->unblessed;
218 unless ( $dont_checkin ) {
219 $qonloan->execute($barcode);
221 my $data = $qonloan->fetchrow_hashref;
222 my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
224 $item_unblessed->{onloan} = undef;
225 $item_unblessed->{datelastseen} = dt_from_string;
227 push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
231 push @scanned_items, $item_unblessed;
233 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
237 $template->param( date => $date );
238 $template->param( errorloop => \@errorloop ) if (@errorloop);
241 # Build inventorylist: used as result list when you do not pass barcodes
242 # This list is also used when you want to compare with barcodes
243 my ( $inventorylist, $rightplacelist );
244 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
245 ( $inventorylist ) = GetItemsForInventory({
246 minlocation => $minlocation,
247 maxlocation => $maxlocation,
248 class_source => $class_source,
249 location => $location,
250 ignoreissued => $ignoreissued,
251 datelastseen => $datelastseen,
252 branchcode => $branchcode,
255 statushash => $staton,
256 ignore_waiting_holds => $ignore_waiting_holds,
259 # Build rightplacelist used to check if a scanned item is in the right place.
260 if( @scanned_items ) {
261 ( $rightplacelist ) = GetItemsForInventory({
262 minlocation => $minlocation,
263 maxlocation => $maxlocation,
264 class_source => $class_source,
265 location => $location,
266 ignoreissued => undef,
267 datelastseen => undef,
268 branchcode => $branchcode,
272 ignore_waiting_holds => $ignore_waiting_holds,
274 # Convert the structure to a hash on barcode
276 map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
280 # Report scanned items that are on the wrong place, or have a wrong notforloan
281 # status, or are still checked out.
282 for ( my $i = 0; $i < @scanned_items; $i++ ) {
284 my $item = $scanned_items[$i];
286 $item->{notforloancode} = $item->{notforloan}; # save for later use
287 my $fc = $item->{'frameworkcode'} || '';
289 # Populating with authorised values description
290 foreach my $field (qw/ location notforloan itemlost damaged withdrawn /) {
291 my $av = Koha::AuthorisedValues->get_description_by_koha_field(
292 { frameworkcode => $fc, kohafield => "items.$field", authorised_value => $item->{$field} } );
293 if ( $av and defined $item->{$field} and defined $av->{lib} ) {
294 $item->{$field} = $av->{lib};
298 # If we have scanned items with a non-matching notforloan value
299 if( none { $item->{'notforloancode'} eq $_ } @notforloans ) {
300 $item->{problems}->{changestatus} = 1;
301 additemtoresults( $item, $results );
304 # Check for items shelved out of order
307 my $previous_item = $scanned_items[ $i - 1 ];
308 if ( $previous_item && $item->{cn_sort} lt $previous_item->{cn_sort} ) {
309 $item->{problems}->{out_of_order} = 1;
310 additemtoresults( $item, $results );
313 unless ( $i == scalar(@scanned_items) ) {
314 my $next_item = $scanned_items[ $i + 1 ];
315 if ( $next_item && $item->{cn_sort} gt $next_item->{cn_sort} ) {
316 $item->{problems}->{out_of_order} = 1;
317 additemtoresults( $item, $results );
322 # Report an item that is checked out (unusual!) or wrongly placed
323 if( $item->{onloan} ) {
324 $item->{problems}->{checkedout} = 1;
325 additemtoresults( $item, $results );
326 next; # do not modify item
327 } elsif( !exists $rightplacelist->{ $item->{barcode} } ) {
328 $item->{problems}->{wrongplace} = 1;
329 additemtoresults( $item, $results );
333 # Compare barcodes with inventory list, report no_barcode and not_scanned.
334 # not_scanned can be interpreted as missing
335 if ( $compareinv2barcd ) {
336 my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
337 for my $item ( @$inventorylist ) {
338 my $barcode = $item->{barcode};
340 $item->{problems}->{no_barcode} = 1;
341 } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
344 $item->{problems}->{not_scanned} = 1;
346 additemtoresults( $item, $results );
350 # Construct final results, add biblio information
351 my $loop = $uploadbarcodes
352 ? [ map { $results->{$_} } keys %$results ]
353 : $inventorylist // [];
354 for my $item ( @$loop ) {
355 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
356 $item->{title} = $biblio->title;
357 $item->{author} = $biblio->author;
361 moddatecount => $moddatecount,
367 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
368 eval {use Text::CSV};
369 my $csv = Text::CSV->new or
370 die Text::CSV->error_diag ();
371 binmode STDOUT, ":encoding(UTF-8)";
372 print $input->header(
374 -attachment => 'inventory.csv',
377 my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
378 foreach my $key ( keys %$columns_def_hashref ) {
380 $key =~ s/[^\.]*\.//;
381 $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
382 $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
386 for my $key (qw / biblioitems.title biblio.author
387 items.barcode items.itemnumber
388 items.homebranch items.location
389 items.itemcallnumber items.notforloan
390 items.itemlost items.damaged
391 items.withdrawn items.stocknumber
393 push @translated_keys, $columns_def_hashref->{$key};
395 push @translated_keys, 'problem' if $uploadbarcodes;
397 $csv->combine(@translated_keys);
398 print $csv->string, "\n";
400 my @keys = qw/ title author barcode itemnumber homebranch location itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
401 for my $item ( @$loop ) {
403 for my $key (@keys) {
404 push @line, $item->{$key};
407 foreach my $key ( keys %{$item->{problems}} ) {
408 if( $key eq 'wrongplace' ) {
409 $errstr .= "wrong place,";
410 } elsif( $key eq 'changestatus' ) {
411 $errstr .= "unknown notforloan status,";
412 } elsif( $key eq 'not_scanned' ) {
413 $errstr .= "missing,";
414 } elsif( $key eq 'no_barcode' ) {
415 $errstr .= "no barcode,";
416 } elsif( $key eq 'checkedout' ) {
417 $errstr .= "checked out,";
422 $csv->combine(@line);
423 print $csv->string, "\n";
425 # Adding not found barcodes
426 foreach my $error (@errorloop) {
428 if ($error->{'ERR_BARCODE'}) {
429 push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
430 push @line, "barcode not found";
431 $csv->combine(@line);
432 print $csv->string, "\n";
438 output_html_with_http_headers $input, $cookie, $template->output;
440 sub additemtoresults {
441 my ( $item, $results ) = @_;
442 my $itemno = $item->{itemnumber};
443 # since the script appends to $item, we can just overwrite the hash entry
444 $results->{$itemno} = $item;