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');
35 use C4::Reports::Guided; #_get_column_defs
40 use Koha::AuthorisedValues;
41 use Koha::BiblioFrameworks;
42 use List::MoreUtils qw( none );
44 my $minlocation=$input->param('minlocation') || '';
45 my $maxlocation=$input->param('maxlocation');
46 $maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation );
47 my $location=$input->param('location') || '';
48 my $ignoreissued=$input->param('ignoreissued');
49 my $datelastseen = $input->param('datelastseen'); # last inventory date
50 my $branchcode = $input->param('branchcode') || '';
51 my $branch = $input->param('branch');
52 my $op = $input->param('op');
53 my $compareinv2barcd = $input->param('compareinv2barcd');
54 my $dont_checkin = $input->param('dont_checkin');
55 my $out_of_order = $input->param('out_of_order');
57 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
58 { template_name => "tools/inventory.tt",
62 flagsrequired => { tools => 'inventory' },
67 my @authorised_value_list;
68 my $authorisedvalue_categories = '';
70 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
71 unshift @$frameworks, { frameworkcode => '' };
73 for my $fwk ( @$frameworks ){
74 my $fwkcode = $fwk->{frameworkcode};
75 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
76 my $authcode = $mss->count ? $mss->next->authorised_value : undef;
77 if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
78 $authorisedvalue_categories.="$authcode ";
79 my $data=GetAuthorisedValues($authcode);
80 foreach my $value (@$data){
81 $value->{selected}=1 if ($value->{authorised_value} eq ($location));
83 push @authorised_value_list,@$data;
89 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
91 $hash->{fieldname} = $statfield;
92 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
93 $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
94 if ($hash->{authcode}){
95 my $arr = GetAuthorisedValues($hash->{authcode});
96 if ( $statfield eq 'items.notforloan') {
97 # Add notforloan == 0 to the list of possible notforloan statuses
98 # The lib value is replaced in the template
99 push @$arr, { authorised_value => 0, id => 'stat0' , lib => '__IGNORE__' } if ! grep { $_->{authorised_value} eq '0' } @$arr;
100 @notforloans = map { $_->{'authorised_value'} } @$arr;
102 $hash->{values} = $arr;
103 push @$statuses, $hash;
107 $template->param( statuses => $statuses );
108 my $staton = {}; #authorized values that are ticked
109 for my $authvfield (@$statuses) {
110 $staton->{$authvfield->{fieldname}} = [];
111 for my $authval (@{$authvfield->{values}}){
112 if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
113 push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
119 authorised_values => \@authorised_value_list,
120 today => dt_from_string,
121 minlocation => $minlocation,
122 maxlocation => $maxlocation,
123 location => $location,
124 ignoreissued => $ignoreissued,
125 branchcode => $branchcode,
127 datelastseen => $datelastseen,
128 compareinv2barcd => $compareinv2barcd,
129 uploadedbarcodesflag => $uploadbarcodes ? 1 : 0,
132 # Walk through uploaded barcodes, report errors, mark as seen, check in
136 my $moddatecount = 0;
137 if ( $uploadbarcodes && length($uploadbarcodes) > 0 ) {
138 my $dbh = C4::Context->dbh;
139 my $date = dt_from_string( scalar $input->param('setdate') );
140 $date = output_pref ( { dt => $date, dateformat => 'iso' } );
142 my $strsth = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
143 my $qonloan = $dbh->prepare($strsth);
144 $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
145 my $qwithdrawn = $dbh->prepare($strsth);
148 my @uploadedbarcodes;
150 my $sth = $dbh->column_info(undef,undef,"items","barcode");
151 my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME');
152 my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE};
156 binmode($uploadbarcodes, ":encoding(UTF-8)");
157 while (my $barcode=<$uploadbarcodes>) {
158 push @uploadedbarcodes, grep { /\S/ } split( /[\n\r,;|-]/, $barcode );
160 for my $barcode (@uploadedbarcodes) {
161 next unless $barcode;
163 if (length($barcode)>$barcode_size) {
166 my $check_barcode = $barcode;
167 $check_barcode =~ s/\p{Print}//g;
168 if (length($check_barcode)>0) { # Only printable unicode characters allowed.
171 next if length($barcode)>$barcode_size;
172 next if ( length($check_barcode)>0 );
173 push @barcodes,$barcode;
175 $template->param( LinesRead => $lines_read );
177 push @errorloop, {'barcode'=>'No valid barcodes!'};
178 $op=''; # force the initial inventory screen again.
181 $template->param( err_length => $err_length,
182 err_data => $err_data );
184 foreach my $barcode (@barcodes) {
185 if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
186 push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
188 my $item = GetItem( '', $barcode );
189 if ( defined $item && $item->{'itemnumber'} ) {
190 # Modify date last seen for scanned items, remove lost status
191 ModItem( { itemlost => 0, datelastseen => $date }, undef, $item->{'itemnumber'} );
193 # update item hash accordingly
194 $item->{itemlost} = 0;
195 $item->{datelastseen} = $date;
196 unless ( $dont_checkin ) {
197 $qonloan->execute($barcode);
199 my $data = $qonloan->fetchrow_hashref;
200 my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
202 $item->{onloan} = undef;
203 $item->{datelastseen} = dt_from_string;
205 push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
209 push @scanned_items, $item;
211 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
215 $template->param( date => $date );
216 $template->param( errorloop => \@errorloop ) if (@errorloop);
219 # Build inventorylist: used as result list when you do not pass barcodes
220 # This list is also used when you want to compare with barcodes
221 my ( $inventorylist, $rightplacelist );
222 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
223 ( $inventorylist ) = GetItemsForInventory({
224 minlocation => $minlocation,
225 maxlocation => $maxlocation,
226 location => $location,
227 ignoreissued => $ignoreissued,
228 datelastseen => $datelastseen,
229 branchcode => $branchcode,
232 statushash => $staton,
235 # Build rightplacelist used to check if a scanned item is in the right place.
236 if( @scanned_items ) {
237 ( $rightplacelist ) = GetItemsForInventory({
238 minlocation => $minlocation,
239 maxlocation => $maxlocation,
240 location => $location,
241 ignoreissued => undef,
242 datelastseen => undef,
243 branchcode => $branchcode,
248 # Convert the structure to a hash on barcode
250 map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
254 # Report scanned items that are on the wrong place, or have a wrong notforloan
255 # status, or are still checked out.
256 for ( my $i = 0; $i < @scanned_items; $i++ ) {
258 my $item = $scanned_items[$i];
260 $item->{notforloancode} = $item->{notforloan}; # save for later use
261 my $fc = $item->{'frameworkcode'} || '';
263 # Populating with authorised values description
264 foreach my $field (qw/ location notforloan itemlost damaged withdrawn /) {
265 my $av = Koha::AuthorisedValues->get_description_by_koha_field(
266 { frameworkcode => $fc, kohafield => "items.$field", authorised_value => $item->{$field} } );
267 if ( $av and defined $item->{$field} and defined $av->{lib} ) {
268 $item->{$field} = $av->{lib};
272 # If we have scanned items with a non-matching notforloan value
273 if( none { $item->{'notforloancode'} eq $_ } @notforloans ) {
274 $item->{problems}->{changestatus} = 1;
275 additemtoresults( $item, $results );
278 # Check for items shelved out of order
281 my $previous_item = $scanned_items[ $i - 1 ];
282 if ( $previous_item && $item->{cn_sort} lt $previous_item->{cn_sort} ) {
283 $item->{problems}->{out_of_order} = 1;
284 additemtoresults( $item, $results );
287 unless ( $i == scalar(@scanned_items) ) {
288 my $next_item = $scanned_items[ $i + 1 ];
289 if ( $next_item && $item->{cn_sort} gt $next_item->{cn_sort} ) {
290 $item->{problems}->{out_of_order} = 1;
291 additemtoresults( $item, $results );
296 # Report an item that is checked out (unusual!) or wrongly placed
297 if( $item->{onloan} ) {
298 $item->{problems}->{checkedout} = 1;
299 additemtoresults( $item, $results );
300 next; # do not modify item
301 } elsif( !exists $rightplacelist->{ $item->{barcode} } ) {
302 $item->{problems}->{wrongplace} = 1;
303 additemtoresults( $item, $results );
307 # Compare barcodes with inventory list, report no_barcode and not_scanned.
308 # not_scanned can be interpreted as missing
309 if ( $compareinv2barcd ) {
310 my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
311 for my $item ( @$inventorylist ) {
312 my $barcode = $item->{barcode};
314 $item->{problems}->{no_barcode} = 1;
315 } elsif ( grep /^$barcode$/, @scanned_barcodes ) {
318 $item->{problems}->{not_scanned} = 1;
320 additemtoresults( $item, $results );
324 # Construct final results, add biblio information
325 my $loop = $uploadbarcodes
326 ? [ map { $results->{$_} } keys %$results ]
327 : $inventorylist // [];
328 for my $item ( @$loop ) {
329 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
330 $item->{title} = $biblio->title;
331 $item->{author} = $biblio->author;
335 moddatecount => $moddatecount,
341 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
342 eval {use Text::CSV};
343 my $csv = Text::CSV->new or
344 die Text::CSV->error_diag ();
345 binmode STDOUT, ":encoding(UTF-8)";
346 print $input->header(
348 -attachment => 'inventory.csv',
351 my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
352 foreach my $key ( keys %$columns_def_hashref ) {
354 $key =~ s/[^\.]*\.//;
355 $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
356 $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
360 for my $key (qw / biblioitems.title biblio.author
361 items.barcode items.itemnumber
362 items.homebranch items.location
363 items.itemcallnumber items.notforloan
364 items.itemlost items.damaged
365 items.withdrawn items.stocknumber
367 push @translated_keys, $columns_def_hashref->{$key};
369 push @translated_keys, 'problem' if $uploadbarcodes;
371 $csv->combine(@translated_keys);
372 print $csv->string, "\n";
374 my @keys = qw/ title author barcode itemnumber homebranch location itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
375 for my $item ( @$loop ) {
377 for my $key (@keys) {
378 push @line, $item->{$key};
381 foreach my $key ( keys %{$item->{problems}} ) {
382 if( $key eq 'wrongplace' ) {
383 $errstr .= "wrong place,";
384 } elsif( $key eq 'changestatus' ) {
385 $errstr .= "unknown notforloan status,";
386 } elsif( $key eq 'not_scanned' ) {
387 $errstr .= "missing,";
388 } elsif( $key eq 'no_barcode' ) {
389 $errstr .= "no barcode,";
390 } elsif( $key eq 'checkedout' ) {
391 $errstr .= "checked out,";
396 $csv->combine(@line);
397 print $csv->string, "\n";
399 # Adding not found barcodes
400 foreach my $error (@errorloop) {
402 if ($error->{'ERR_BARCODE'}) {
403 push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
404 push @line, "barcode not found";
405 $csv->combine(@line);
406 print $csv->string, "\n";
412 output_html_with_http_headers $input, $cookie, $template->output;
414 sub additemtoresults {
415 my ( $item, $results ) = @_;
416 my $itemno = $item->{itemnumber};
417 # since the script appends to $item, we can just overwrite the hash entry
418 $results->{$itemno} = $item;