Bug 14393: Add collection code filter to inventory
[koha.git] / tools / inventory.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2009 Biblibre S.A
4 # John Soros <john.soros@biblibre.com>
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use Modern::Perl;
22
23 #need to open cgi and get the fh before anything else opens a new cgi context (see C4::Auth)
24 use CGI qw ( -utf8 );
25 my $input = CGI->new;
26 my $uploadbarcodes = $input->param('uploadbarcodes');
27 my $barcodelist = $input->param('barcodelist');
28
29 use C4::Auth qw( get_template_and_user );
30 use C4::Context;
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 );
37
38 use Koha::Biblios;
39 use Koha::DateUtils qw( dt_from_string output_pref );
40 use Koha::AuthorisedValues;
41 use Koha::BiblioFrameworks;
42 use Koha::ClassSources;
43 use Koha::Items;
44
45 use List::MoreUtils qw( none );
46
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');
62
63 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
64     {   template_name   => "tools/inventory.tt",
65         query           => $input,
66         type            => "intranet",
67         flagsrequired   => { tools => 'inventory' },
68     }
69 );
70
71 my @authorised_value_list;
72 my $authorisedvalue_categories = '';
73
74 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
75 unshift @$frameworks, { frameworkcode => '' };
76
77 my @collections = ();
78 my @collection_codes = ();
79
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));
89       }
90       push @authorised_value_list,@$data;
91     }
92 }
93
94 my $statuses = [];
95 my @notforloans;
96 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
97     my $hash = {};
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;
108         }
109         $hash->{values} = $arr;
110         push @$statuses, $hash;
111     }
112 }
113
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};
121         }
122     }
123 }
124
125 # if there's a list of not for loans types selected use it rather than
126 # the full set.
127 @notforloans = @{$staton->{'items.notforloan'}} if defined $staton->{'items.notforloan'} and scalar @{$staton->{'items.notforloan'}} > 0;
128
129 my @class_sources = Koha::ClassSources->search({ used => 1 })->as_list;
130 my $pref_class = C4::Context->preference("DefaultClassificationSource");
131
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 . "'";
137     }
138 }
139
140 $template->param(
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,
148     branch                   => $branch,
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,
156     ccode                    => $ccode,
157 );
158
159 # Walk through uploaded barcodes, report errors, mark as seen, check in
160 my $results = {};
161 my @scanned_items;
162 my @errorloop;
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);
168
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);
173
174     my @barcodes;
175     my @uploadedbarcodes;
176
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};
180     my $err_length=0;
181     my $err_data=0;
182     my $lines_read=0;
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 );
188         }
189     } else {
190         push @uploadedbarcodes, split(/\s\n/, scalar $input->param('barcodelist') );
191         $uploadbarcodes = $barcodelist;
192     }
193     for my $barcode (@uploadedbarcodes) {
194         next unless $barcode;
195
196         $barcode = barcodedecode($barcode);
197
198         ++$lines_read;
199         if (length($barcode)>$barcode_size) {
200             $err_length += 1;
201         }
202         my $check_barcode = $barcode;
203         $check_barcode =~ s/\p{Print}//g;
204         if (length($check_barcode)>0) { # Only printable unicode characters allowed.
205             $err_data += 1;
206         }
207         next if length($barcode)>$barcode_size;
208         next if ( length($check_barcode)>0 );
209         push @barcodes,$barcode;
210     }
211     $template->param( LinesRead => $lines_read );
212     if (! @barcodes) {
213         push @errorloop, {'barcode'=>'No valid barcodes!'};
214         $op=''; # force the initial inventory screen again.
215     }
216     else {
217         $template->param( err_length => $err_length,
218                           err_data   => $err_data );
219     }
220     foreach my $barcode (@barcodes) {
221         if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
222             push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
223         } else {
224             my $item = Koha::Items->find({barcode => $barcode});
225             if ( $item ) {
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;
229                 $moddatecount++;
230                 unless ( $dont_checkin ) {
231                     $qonloan->execute($barcode);
232                     if ($qonloan->rows){
233                         my $data = $qonloan->fetchrow_hashref;
234                         my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
235                         if( $doreturn ) {
236                             $item_unblessed->{onloan} = undef;
237                             $item_unblessed->{datelastseen} = dt_from_string;
238                         } else {
239                             push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
240                         }
241                     }
242                 }
243                 push @scanned_items, $item_unblessed;
244             } else {
245                 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
246             }
247         }
248     }
249     $template->param( date => output_pref ( { str => $date, dateformat => 'iso' } ) );
250     $template->param( errorloop => \@errorloop ) if (@errorloop);
251 }
252
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,
265       branch       => $branch,
266       offset       => 0,
267       statushash   => $staton,
268       ccode        => $ccode,
269       ignore_waiting_holds => $ignore_waiting_holds,
270       itemtypes    => \@selected_itemtypes,
271     });
272 }
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,
284       branch       => $branch,
285       offset       => 0,
286       statushash   => undef,
287       ignore_waiting_holds => $ignore_waiting_holds,
288       itemtypes    => \@selected_itemtypes,
289       ccode        => $ccode,
290     });
291     # Convert the structure to a hash on barcode
292     $rightplacelist = {
293         map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
294     };
295
296 }
297
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++ ) {
301
302     my $item = $scanned_items[$i];
303
304     $item->{notforloancode} = $item->{notforloan}; # save for later use
305     my $fc = $item->{'frameworkcode'} || '';
306
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};
313         }
314     }
315
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 );
320     }
321
322     # Check for items shelved out of order
323     if ($out_of_order) {
324         unless ( $i == 0 ) {
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 );
329             }
330         }
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 );
336             }
337         }
338     }
339
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 );
348     }
349 }
350
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};
357         if( !$barcode ) {
358             $item->{problems}->{no_barcode} = 1;
359         } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) {
360             next;
361         } else {
362             $item->{problems}->{not_scanned} = 1;
363         }
364         additemtoresults( $item, $results );
365     }
366 }
367
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;
376 }
377
378 $template->param(
379     moddatecount => $moddatecount,
380     loop         => $loop,
381     op           => $op,
382 );
383
384 # Export to csv
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(
391         -type       => 'text/csv',
392         -attachment => 'inventory.csv',
393     );
394
395     my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
396     foreach my $key ( keys %$columns_def_hashref ) {
397         my $initkey = $key;
398         $key =~ s/[^\.]*\.//;
399         $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
400         $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
401     }
402
403     my @translated_keys;
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
410                       / ) {
411        push @translated_keys, $columns_def_hashref->{$key};
412     }
413     push @translated_keys, 'problem' if $uploadbarcodes;
414
415     $csv->combine(@translated_keys);
416     print $csv->string, "\n";
417
418     my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /;
419     for my $item ( @$loop ) {
420         my @line;
421         for my $key (@keys) {
422             push @line, $item->{$key};
423         }
424         my $errstr = '';
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,";
436             }
437         }
438         $errstr =~ s/,$//;
439         push @line, $errstr;
440         $csv->combine(@line);
441         print $csv->string, "\n";
442     }
443     # Adding not found barcodes
444     foreach my $error (@errorloop) {
445         my @line;
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";
451         }
452     }
453     exit;
454 }
455
456 output_html_with_http_headers $input, $cookie, $template->output;
457
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;
463 }